Javascript - 点击更改DIV背景

时间:2013-12-23 10:21:07

标签: javascript jquery

当点击箭头时,我正在使用JQuery扩展和收缩DIV。箭头应指向上/下,具体取决于DIV是否已展开。

我试过这个,但似乎没有用。箭头保留为默认向下箭头。上滑/下滑工作正常,但图像不会改变。任何人都可以解释原因吗?

         function toggle_visibility(id) {
             $e = $("#" + id);
             $arrow = $("#arrow" + id);

             if ($e.is(':visible')){
                 $e.slideUp("slow");
                 $arrow.css('background-image', 'url(../images/downarrow.png)');
             }else{
                $e.slideDown("slow");
                 $arrow.css('background-image', 'url(../images/uparrow.png)');
             }
         }

6 个答案:

答案 0 :(得分:3)

这应该有效:

function toggle_visibility(id) {
         $e = $("#"+id);

         if ($e.is(':visible')){
             $e.slideUp("slow");
             $e.css('background-image', 'url(../images/downarrow.png)');
         }else{
            $e.slideDown("slow");
             $e.css('background-image', 'url(../images/uparrow.png)');
         }
     }

答案 1 :(得分:2)

工作jsfiddle:http://jsfiddle.net/patelmilanb1/9YA67/

<div id="arrow">Hello</div>

toggle_visibility($('#arrow'));

function toggle_visibility(id) {
    var $element = $(id);

    if ($element.is(':visible')) {
        $element.slideUp("slow");
        $element.css('background-image', 'url(../images/downarrow.png)');
    } else {
        $element.slideDown("slow");
        $element.css('background-image', 'url(../images/uparrow.png)');
    }
}

更新:在这种情况下,课程可以派上用场。因为它更具可读性,并且可以将CSS保留在javascript之外。

更新了课程:http://jsfiddle.net/patelmilanb1/9YA67/1/

toggle_visibility($('#arrow'));

function toggle_visibility(id) {
    var $element = $(id);

    if ($element.is(':visible')) {
        $element.addClass("down").removeClass("up");
    } else {
        $element.addClass("up").removeClass("down");
    }
} 

答案 2 :(得分:1)

你的语法错误

$(e).css('background-image', 'url(../images/downarrow.png)');

将其替换为

$e.css('background-image', 'url(../images/downarrow.png)');

答案 3 :(得分:0)

$(e).css(...)应为$e.css(...)

答案 4 :(得分:0)

试试这种方式

var $e = $("#"+id)

答案 5 :(得分:0)

通过jQuery中的css('attributename','attributevalue')函数设置任何值都会将该属性添加到元素的内联样式中。在检查器中,它经常被标记为element.style

除了发布的答案之外,我希望你只通过类来做这个,然后你可以通过添加/删除元素中的类来创建一个单独的类与备用背景图像和切换类,这不会出现在element.style中,它只是切换类,而是在检查器中显示。

相关问题