[英]What's the proper syntax, in JavaScript, for changing css via conditional statements?
這是我所擁有的,我知道這是不對的。 基本上,我試圖說,“如果div的高度為34,則將背景圖像更改為此jpg。”
if ( ".three" == height:"445" ) {".three.style.background-image"= 'url(images/2.jpg)'};
提前致謝!
假設您的HTML符合以下條件:
<div class="three" style="height: 445px;">
<p>Some arbitrary content.</p>
</div>
然后,以下將起作用:
var elems = document.getElementsByClassName('three');
for (var i = 0, len = elems.length; i < len; i++){
if (parseInt(elems[i].style.height, 10) == 445) {
elems[i].style.backgroundImage = 'url(images/2.png)';
}
}
JS Fiddle演示 ,使用background-color
而不是background-image
來簡化)。
但是,如果您使用CSS來設置元素的樣式:
.three {
height: 445px;
}
然后你需要使用window.getComputedStyle()
:
var elems = document.getElementsByClassName('three');
for (var i = 0, len = elems.length; i < len; i++){
console.log(parseInt(window.getComputedStyle(elems[i], null).height, 10));
if (parseInt(window.getComputedStyle(elems[i], null).height, 10) == 445) {
elems[i].style.backgroundColor = 'red';
}
}
JS小提琴演示 ,(使用,如上所述, background-color
而不是background=image
)。
如果要使用JavaScript庫,則可以在某種程度上進行簡化。 使用jQuery(例如,盡管我不是特別提倡jQuery,但它只是我最熟悉的庫),以上內容可以重寫為:
$('.three').css('background-image', function(){
return $(this).height() == 445 ? 'images/2.png' : '';
});
JS小提琴演示 ,(再次使用background-color
而不是background=image
)。
請注意,Internet Explorer與大多數瀏覽器的工作方式不同,在那個window.getComputedStyle()
不可用,但是有currentStyle()
,但是沒有Windows,我無法提供有關如何使用它的建議。
有關JavaScript的指導和參考,我建議(幾乎所有其他內容)閱讀Mozilla Developer Network的JavaScript文檔 。
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.