jQuery .css() 方法无效

jQuery .css() method not working

我有一段代码使用 jQuery .css() 方法来修改 DIV 的样式,但它不起作用。这是我的代码的简化版本,它复制了这个问题。

HTML:

<input type="radio" name="show" id="showleft" value="showleft">Left
<input type="radio" name="show" id="showright" value="showright">Right
<div id="cfwrapper">XXXXXXXXX</div>

CSS:

#cfwrapper {
    bottom: 10px;
    left: 30px;
    position: fixed;
}

JavaScript:

$("input:radio[name=show]").click(function(event){
    if (event.target.id == 'showleft') {
        // remove property 'right:30px'
        // add property 'left:30px'
    } else if (event.target.id == 'showright') {
        $('#cfwrapper').css('left',''); // remove property 'left:30px'
        // add property 'right:30px'
    }
});

上面代码中发生的事情是 $('#cfwrapper').css('left',''); 行不起作用。我希望它从 "cfwrapper" 中删除 'left' 属性("XXXXXXXXX" 然后向左移动 30px)然后我会使用类似的语句 - $('#cfwrapper').css('right','30px'); - 添加"right" 属性,这样 "XXXXXXXXX" 就会转到页面的右侧,但它不起作用。

谁能告诉我为什么它不起作用?它不应该起作用吗?

JSFiddle:http://jsfiddle.net/fidnut/hLqngbsb/

请参阅 this question 的答案。

来自jQuery docs

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

一种更易于维护的方法是 add/remove 类 来控制样式:

http://jsfiddle.net/0hh80mkd/2/

试试这个 .css('left','auto')

$("input:radio[name=show]").click(function(event){
    if (event.target.id == 'showleft') {
        document.getElementById('op').innerHTML='Left side';
        $('#cfwrapper').css({'left':'30px','right':'auto'});

    } else if (event.target.id == 'showright') {
        document.getElementById('op').innerHTML='Right side';
         $('#cfwrapper').css({'left':'auto','right':'30px'});
    }
});

http://jsfiddle.net/hLqngbsb/2/

使用class

.cfwrapper {
    bottom: 10px;
    left: 30px;
    position: fixed;
}

.cfwrapperDis{
    bottom: 10px;
    left: 30px;
    position: fixed;
}

然后

$("input:radio[name=show]").click(function(event){
    if (event.target.id == 'showleft') {
        // remove property 'right:30px'
        // add property 'left:30px'
    } else if (event.target.id == 'showright') {
        $('#cfwrapper').removeClass("cfwrapper").addClass("cfwrapperDis"); // remove property 'left:30px'
        // add property 'right:30px'
    }
});