我想根据点击的DIV的网址更改点击背景图片
我的逻辑如下:
当用户点击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>
的Javascript
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";
}
}
然而,当我点击手风琴(索引)标题Div时,图像会在第一次单击时发生变化,但是当我再次单击时图像不会变回。为什么会这样呢?我在这里缺少什么?
答案 0 :(得分:0)
您可以使用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/