使用CSS和Javascript控制網頁圖片寬度的大小

來源:互聯網
上載者:User

JorWang の 小喇叭:『 最近比較忙啊,暫時不更新了,大家玩得開心點哦!O(∩_∩)O~ 』

剛剛看到兩個控制網頁圖片寬度的大小的方法,覺得很好很方便,特此分享給大家。

第一個方法是使用CSS來實現控制大小:

img{border:0;margin:0;padding:0;max-width:590px;width:expression(this.width>590?"590px":this.width); max-height:590px;height:expression(this.height>590?"590px":this.height);}

如果你要相容IE6的話,可以配合使用以前介紹的這個Javascript指令碼。

第二個方法是使用Javascript來控制控制網頁圖片寬度的大小:

function set_img_size(obj, width){    if (!obj) return ;    if (!width) {        width = obj.clientWidth * 0.9;        if (width < 400) return; /*設定圖片的限定寬度*/    }    img_items = obj.getElementsByTagName("img")    if (img_items)  {        for (i=0; i<img_items.length; i++) {            var s_width = img_items[i].width;            var s_height = img_items[i].height;            if (s_width > width) {                img_items[i].style.width = width + "px";                if (s_height == img_items[i].height) {                    img_items[i].style.height = ((width / s_width) * img_items[i].height) + "px";                }                img_items[i].onclick = function() {window.open(this.src)};                img_items[i].style.cursor = "pointer";                img_items[i].alt = "點擊查看原始大小";            }        }    }}   function selfadaptation_size() {    if (typeof(content_img_width) == 'undefined')        set_img_size(document.getElementById("posts")); /*控製圖片所在的元素ID號*/    else        set_img_size(document.getElementById("posts"), content_img_width); /*控製圖片所在的元素ID號*/       set_img_size(document.getElementById("custom")); /*控製圖片所在的元素ID號*/}   if (window.addEventListener)    window.addEventListener("load", selfadaptation_size, false);else if (window.attachEvent)    window.attachEvent("onload", selfadaptation_size);else    window.onload = selfadaptation_size;

如果你有更好更簡潔的方法,分享給我吧,謝謝了!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.