javascript - 关于jquery获取style特性值
黄舟
黄舟 2017-04-11 09:41:04
[JavaScript讨论组]

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

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
PHPz

因为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

明白问题了吧

大家讲道理

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号