开发者社区 问答 正文

关于jquery获取style特性值

用JQuery获取元素的style特性里的width属性值并复制给另外一个元素的value值,发现并没有效果,.show元素还是空,console控制台输出style特性的width属性值并不是50%,而是px指,请问这是怎么回事啊?
screenshot

展开
收起
小旋风柴进 2016-05-31 11:34:05 1978 分享 版权
1 条回答
写回答
取消 提交回答
  • 因为jquery获取css属性时,获取的是计算后的属性
    jquery.css()

    function (elem, name, extra) {
        var ret, hooks;
    
        // Make sure that we're working with the right name
        name = jQuery.camelCase(name);
        hooks = jQuery.cssHooks[name];
        name = jQuery.cssProps[name] || name;
    
        // cssFloat needs a special treatment
        if (name === "cssFloat") {
            name = "float";
        }
    
        // If a hook was provided get the computed value from there 在这里
        if (hooks && "get" in hooks && (ret = hooks.get(elem, true, extra)) !== undefined) {
            return ret;
    
            // Otherwise, if a way to get the computed value exists, use that
        } else if (curCSS) {
            return curCSS(elem, name);
        }
    }

    所以出来的是px值。若想要获得百分数值可以这样
    parseInt($('.show').css('width'))*100/parseInt($('body').css('width'))+"%"
    另外你给.show属性赋值的方法我看着好像是不对的,建议直接用.width()就可以了。
    再另外, style="width: 50%" 要不然.test的width都设置不了

    2019-07-17 19:21:42
    赞同 展开评论
问答分类:
问答标签:
问答地址: