【问题标题】:How to remove only one style property with jQuery?如何使用 jQuery 只删除一个样式属性?
【发布时间】:2011-08-22 12:32:49
【问题描述】:

我有一个带有此属性的 div style="-moz-user-select:none; position:static !important;"。 我需要删除-moz-user-select 尝试使用$(selector).css(),但我不知道要设置什么值,因为它是"none"

【问题讨论】:

  • 如果是none,为什么要去掉呢?如果您需要将其更改为另一个值here 是一个有效值列表

标签: jquery css


【解决方案1】:

css() 的文档说,将样式属性设置为空字符串将删除该属性,如果它不驻留在样式表中:

设置样式属性的值 到一个空字符串——例如 $('#mydiv').css('color', '') — 删除 元素的那个属性,如果它 已经直接申请了, 是否在 HTML 样式属性中, 通过 jQuery 的 .css() 方法,或者 通过直接 DOM 操作 样式属性。然而,它并没有, 删除已应用的样式 在样式表中使用 CSS 规则或 <style> 元素。

由于你的样式是内联的,你可以这样写:

$(selector).css("-moz-user-select", "");

【讨论】:

  • @KevinFegan document.getElementById('mydiv').style.removeProperty('-moz-user-select')
【解决方案2】:

我知道这个问题是关于 jQuery 的,但想添加(对于像我这样的人,他们从谷歌在这里偶然发现)一个带有 vanilla js 的解决方案:

(基于我的GIST

下面是该方法的细分,但删除了 cmets,它非常小而简单的单行 split->filter->join

const removeStyleProp = (elm, prop) => 
  elm.style.cssText = elm.style.cssText // "top: 0px; bottom: 50px; text-align: right;"
    .split('; ') // ["top: 0px", "bottom: 50px", "right: 2px", "text-align: right;"]
    .filter(p => !p.startsWith(prop) ) // ["top: 0px", "bottom: 50px", "text-align: right;"]
    .join(';');

// usage:
removeStyleProp(test, 'right')
console.log( test.style.cssText )
<div id='test' style='top:0;right:5px;bottom:50px;right:2px;text-align:right;'></div>

也可以使用正则表达式完成

【讨论】:

    【解决方案3】:

    您也可以将“-moz-user-select:none”替换为“-moz-user-select:inherit”。如果没有定义父样式,这将从任何父样式或默认样式继承样式值。

    【讨论】:

    • 继承没有删除
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2011-09-09
    • 2012-08-12
    • 2011-07-20
    • 1970-01-01
    • 2012-11-17
    相关资源
    最近更新 更多