关于jquery获取style特性值

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

阅读 11.8k
3 个回答

因为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都设置不了

var width = $(".test").css("width"); // "200px"

var width = $(".test").width(); // 200

明白问题了吧

你div.show为空是因为你设置的val()只对input框有效,对div无效 ,你可以用text()方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题