2

我正在为 div 元素使用边框样式。我想使用 jQuery 动态更改边框样式。

当我在 jQuery 中获得边框样式时,有时在 Chrome 中它可以正常工作,有时不能。在 IE 中它不起作用,在 Mozilla 中它工作正常。

下面是我的代码:

// 这是 HTML 元素

<div id="blankcontainer1" style="overflow:hidden; width:100px; 
                          height:100px; background-color:#a2a2a2; 
                          border-top-width:1px; 
                          border-top-style:solid; 
                          border-top-color:#fa0000; 
                          border-right:1px solid #666666; 
                          border-bottom:1px solid #666666; 
                          border-left:1px solid #666666; 
                          border-top-left-radius:0px; 
                          border-top-right-radius:0px; 
                          border-bottom-left-radius:0px; 
                          border-bottom-right-radius:0px;"></div>

// 这是Javascript

var elestyle = $("#blankcontainer1").attr("style");
var splitstyle = elestyle.split(";");

var i = 0;
while(i < splitstyle.length){
    var attrstyle = splitstyle[i].split(":");
    if($.trim(attrstyle[0]) == "border-top-width")
        $("#containersetting #btsize").val($.trim(attrstyle[1]).substring(0, $.trim(attrstyle[1]).length-2));
    if($.trim(attrstyle[0]) == "border-top-style")
        $("#containersetting #btstyle").val($.trim(attrstyle[1]));
    if($.trim(attrstyle[0]) == "border-top-color"){
        var bordtcolor = $.trim(attrstyle[1]);
        if(bordtcolor.indexOf('rgb') !== -1)                 
                bordtcolor=colorToHex(bordtcolor);

        $("#containersetting #btcolor").val(bordtcolor);
    }
}

在上面的代码中,Chrome 样式显示 -

border-top-width: 1px;
border-top-style: solid;
border-top-color: #fa0000;

但有时会显示

border-width: 1px;
border-style: solid;
border-color: rgb(250, 0, 0) rgb(102, 102, 102) rgb(102, 102, 102);

IE风格显示:

border-top:#fa0000 1px solid;

所以,这是由我的 JavaScript 代码失败引起的。你能告诉我这里出了什么问题吗?

4

1 回答 1

3

您可以使用 jQuery 查询样式值 - 如下所示:

var borderTopColor = $('#blankcontainer1').css('border-top-color');

alert(borderTopColor);

这意味着您无需尝试手动解析样式属性。

您还可以使用 jquery-color 插件对样式更改(包括颜色)进行动画处理:

$('#blankcontainer1').animate({
    borderTopColor: '#abcdef'
}, 1000);

最后...如果您在由 CSS 伪类(如:hover)表示的东西上执行此操作,则可以使用 CSS3 过渡:

a {
    -moz-transition:all 0.5s ease;
    -o-transition:all 0.5s ease;
    -webkit-transition:all 0.5s ease;
    transition:all 0.5s ease;
    borderTopColor: #fedcba;
}

a:hover {
    borderTopColor: #abcdef;
}
于 2013-04-10T12:44:11.020 回答