jQuery切换 - 更改图像的背景位置

时间:2014-11-14 17:59:27

标签: javascript jquery toggle

我有一个jQuery切换功能,工作正常:如果我点击dt-tag dd部分向上或向下滑动。就像它应该的那样。 但现在我想扩展切换功能:每次点击dt-tag(向上或向下显示箭头)时,dt-tag中的span元素的背景图像应该改变位置。我尝试使用以下代码完成此操作,但我无法使其工作

         <dt><?php echo $this->__($_filter->getName()) ?><span id="cpl"></span></dt>
         <dd><?php echo $_filter->getHtml() ?></dd>


        jQuery('dd').hide();
        jQuery('dt').click(function() {
            var toggle = jQuery(this).nextUntil('dt');
            toggle.slideToggle();
            jQuery('dd').not(toggle).slideUp();
            jQuery('#cpl').toggleClass('clicked');
        });

       #cpl {
         width: 90px;
         height: 11px;
         display: inline-block;
         margin: 0 0 0 10px;
         background:transparent url('../images/arrow.gif') no-repeat;
         background-position: 0 0;
       }

       #cpl.clicked {
         background-position: 0 -15px;
       }

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

三个步骤:1)给你的跨度一个共同的类而不是ID:

<span class="cpl"></span>

2)将点击功能中的最后一行更改为:

jQuery('dt').click(function() {
    /* your code */
    // this selects only an element with class 'cpl' inside the clicked element
    jQuery('.cpl', this).toggleClass('clicked');
});

3)更改您的CSS以解决课程&#39; cpl&#39;:

.cpl { ... }
.cpl.clicked { ... }

DEMO with three 'dt'