如何使用jQuery仅删除一个样式属性?

136

我有一个具有以下属性的 div 元素:style="-moz-user-select:none; position:static !important;"

我需要移除 -moz-user-select

尝试使用 $(selector).css(),但不知道该设置什么值,因为它是 "none"


如果它是“none”,为什么你需要将它移除?如果你需要将它更改为另一个值,在这里有一个有效值列表:https://developer.mozilla.org/en/CSS/-moz-user-select。 - Chad
3个回答

271

css()的文档说明,如果样式属性不在样式表中,则将该属性设置为空字符串将会移除该属性:

将样式属性的值设置为空字符串 - 例如 $('#mydiv').css('color', '') - 如果该属性已经被直接应用于元素(无论是通过HTML的style属性、jQuery的 .css()方法还是直接操作DOM),则将其从元素中移除。不过,它并不会移除在样式表或者 <style> 元素中应用的样式。

由于您的样式是内联的,因此可以编写:

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

22
@KevinFegan document.getElementById('mydiv').style.removeProperty('-moz-user-select') - xehpuk

0

我知道这个问题是关于jQuery的,但是想要为那些像我一样从Google跌跤到这里的人添加一个使用原生js的解决方案:

(基于我的GIST)

Below is a breakdown of the method, but removing the comments and it's pretty much small and simple one-liner 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”。这将从任何父样式或默认样式继承样式值,如果没有定义父样式。


6
继承并不等于移除。 - Eugen Konkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接