網頁中圖片屬性固定寬度,如何用js改變大小
html默認樣式:
<div class="news_infos" id="newsp">
<p><img src="images/v1.jpg" style="width:300px;height:100px"></p>
</div>
CSS:
.news_infos img { max-width: 650px;height:auto; }
js:
<script type="text/javascript">
var aImg=document.getElementById("newsp").getElementsByTagName('img');
for(var i=0;i<aImg.length;i++){
aImg[i].style.height="100%";
aImg[i].style.width="100%";
}
</script>
或者 方法二:
<script type="text/javascript">
var aImg=document.getElementById("newsp").getElementsByTagName('img');
for(var i=0;i<aImg.length;i++){
aImg[i].style.height="auto";
aImg[i].style.width="auto";
}
</script>
html更改后:
<div class="news_infos" id="newsp">
<p><img src="images/v1.jpg" style="width:100%;height:100%"></p>
</div>
100%這個方案不是很完美,如果圖片上傳的大小沒有超過650,那么PC端圖片會被放大。還有一種解決方案就是,編輯后臺內容的時候,將圖片屬性后面的width,height值都刪掉,讓css來控制就行了。同樣用max-width來控制圖片大小,小圖<650px,圖片不會被更改,>650px,圖片寬度就是650px。,那么手機端就用100%來表示。
方法三 CSS:
.news_infos img { max-width: 650px;height:auto; }
@media only screen and (max-width: 480px) {
.news_infos img { width:100%; }
}
這個的不好的地方就在于,每次編輯圖片屬性,都得刪除后面的width,比較繁瑣。
以上方法,都可以實現,但是100%,和設置寬度這兩種方法都不完美, 如果以前圖多,已經固定了寬度,建議使用方法二