javascript - 关于jquery获取style特性值

查看:73
本文介绍了javascript - 关于jquery获取style特性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

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

这篇关于javascript - 关于jquery获取style特性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆