【问题标题】:Toggle background image of a link for accordion切换手风琴链接的背景图像
【发布时间】:2014-05-07 02:08:12
【问题描述】:

我正在尝试使用 javascript 获取链接背景图像,以便在点击时切换或交换常见问题手风琴展开/可收缩 div。

我已经根据这个 jsfiddle 示例 (http://jsfiddle.net/QwELf/) 完成了工作

你可以在这里看到我的页面 (http://bit.ly/1hfgcGL)

当您第三次单击其中一个切换链接时,问题就出现了。它获取了错误的背景图像,然后与它的外观不同步。

收缩状态的向右箭头 > 和展开状态的向下箭头是它们应该的样子,但相反的显示。

它似乎在 jsfiddle 中运行得很好,点击 3 次或更多点击知道我的问题是什么吗?

脚本

<script type="text/javascript">
  function changeArrow(element){

var arrow = element;

if(arrow.className == 'background_one'){

  arrow.className = 'background_two';

} else {

  arrow.className = 'background_one';

}

}
</script>

CSS

.background_one { text-decoration: none; padding-left: 26px; background: url(http://skmgroupwork.com/suntrust/landingpages/307m/chevright.gif) center left no-repeat;}
.background_two { text-decoration: none; padding-left: 26px; background: url(http://skmgroupwork.com/suntrust/landingpages/307m/chevdown.gif) center left no-repeat;}

HTML

<a class="background_one" data-toggle="collapse" data-target="#demo4"    onClick="changeArrow(this)">If I transfer my balance to a new Access 3 Equity Line, what will my interest rate be?</a>

【问题讨论】:

    标签: javascript css toggle background-image accordion


    【解决方案1】:

    你需要检查它是否有类,而不是如果有,因为你有好几次。当你使用 jQuery 时,你可以使用 .hasClass().addClass()removeCLass()。您可能还想查看.toggleClass()

    function changeArrow(element) {
        var $arrow = $(element);
        if ($arrow.hasClass('background_one')) {
            $arrow.removeClass('background_one');
            $arrow.addClass('background_two');
        } else {
            $arrow.removeClass('background_two');
            $arrow.addClass('background_one');
        }
    }
    

    【讨论】:

    • 谢谢你这工作完美,你的描述帮助我理解逻辑。
    【解决方案2】:

    发生这种情况是因为类名在第二次单击时包含类collapsed

    我用IE的调试器发现了这个:

    也许您可以使用contains 代替equals,如下所示(未经测试,但应该可以):

    function changeArrow(element){
        element.className = (arrow.className.contains('background_one') ? 
                              'background_two' : 
                              'background_one');
    }
    

    【讨论】:

    • 额外的课程似乎不是问题。我的脚本只是执行了错误的功能。
    • @TerriSwiatek 实际上,额外的类的问题。您使用的是=,这是一个直接的字符串比较。 hasClass 不是直接的字符串比较;它查看该类是否存在于 className 中,这本质上是 contains 字符串比较所做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    相关资源
    最近更新 更多