[英]How to Toggle background image based on Image URL using Javascript
我想基於單擊的DIV的URL更改單擊時的背景圖像
我的邏輯如下:
用戶單擊div時
{
If (Background URL = x)
{
change background url property to y
}
else
{
change background url property to x
}
}
這是我使用的代碼
HTML:
<div id="AccordionContainer" class="AccordionContainer">
<div onclick="runAccordion(1);changeArrow(1)">
<div class="AccordionTitle" id="Accordion1Title" onselectstart="return false;" onclick="changeArrow(1);" >
Instructions
</div>
</div>
<div id="Accordion1Content" class="AccordionContent">
<p>Enter in your search parameters</p>
</div>
<div onclick="runAccordion(2);">
<div class="AccordionTitle" id="Accordion2Title" onselectstart="return false;" onclick="changeArrow(2);" >
Colour
</div>
</div>
<div id="Accordion2Content" class="AccordionContent">
[wpv-control field="cultivar-category" type="checkboxes" values="Dark Red" url_param="cultivar-category"]
</div>
</div>
Java腳本
function changeArrow(index)
{
var arrowID = "Accordion" + index + "Title";
var img = document.getElementById(arrowID),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1);
if (bi = "http://www.hadecobulbs.com/wp-content/themes/blankslate/img/accordian-title.png")
{
document.getElementById(arrowID).style.background="url(http://www.hadecobulbs.com/wp-content/themes/blankslate/img/accordian-title-up.png) no-repeat scroll 0 0 transparent";
}
else
{
document.getElementById(arrowID).style.background="url(http://www.hadecobulbs.com/wp-content/themes/blankslate/img/accordian-title.png) no-repeat scroll 0 0 transparent";
}
}
但是,當我單擊Accordion(index)Title Div時,圖像會在第一次單擊時發生變化,但是當我再次單擊時,圖像不會變回原樣。 為什么會這樣呢? 我在這里想念什么?
不用傳遞數字給函數,您可以使用this
函數傳遞元素本身,這意味着您可以大大減少編寫的代碼量。
像這樣在您的div上調用函數
<div class="background_one" onClick="changeArrow(this)"> </div>
使用@ d4rkpr1nc3的注釋設置您的CSS類以更改背景圖像,如下所示
.background_one {
width:188px;
height:32px;
background-image:url('wp-content/themes/blankslate/img/accordian-title-up.png');
}
.background_two {
width:188px;
height:32px;
background-image:url('wp-content/themes/blankslate/img/accordian-title.png');
}
然后在你的函數中做這樣的事情
function changeArrow(element){
var arrow = element;
if(arrow.className == 'background_one'){
arrow.className = 'background_two';
} else {
arrow.className = 'background_one';
}
}
這是一個jsfiddle- http://jsfiddle.net/QwELf/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.