gpt4 book ai didi

jquery - 是否可以使用 jQuery 删除内联样式?

转载 作者:IT王子 更新时间:2023-10-29 03:23:48 26 4
gpt4 key购买 nike

一个 jQuery 插件正在应用内联样式 (display:block)。我觉得很懒,想用 display:none 覆盖它。

什么是最好的(懒惰的)方式?

最佳答案

更新:虽然以下解决方案有效,但还有一种更简单的方法。见下文。


这是我想出的,我希望这对您或其他任何人都有用:

$('#element').attr('style', function(i, style)
{
return style && style.replace(/display[^;]+;?/g, '');
});

这将删除该内联样式。

我不确定这是否是您想要的。你想覆盖它,正如已经指出的那样,很容易通过 $('#element').css('display', 'inline') 完成。 .

我正在寻找的是一个完全删除内联样式的解决方案。我需要这个用于我正在编写的插件,我必须临时设置一些内联 CSS 值,但稍后想删​​除它们;我希望样式表收回控制权。我可以通过存储它的所有原始值然后将它们放回内联来实现,但我觉得这个解决方案更简洁。


这里是插件格式:

(function($)
{
$.fn.removeStyle = function(style)
{
var search = new RegExp(style + '[^;]+;?', 'g');

return this.each(function()
{
$(this).attr('style', function(i, style)
{
return style && style.replace(search, '');
});
});
};
}(jQuery));

如果您在脚本之前的页面中包含此插件,您可以调用

$('#element').removeStyle('display');

这应该可以解决问题。


更新:我现在意识到这一切都是徒劳的。您可以简单地将其设置为空白:

$('#element').css('display', '');

它会自动为您删除。

这是来自 the docs 的引述:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

我不认为 jQuery 在这里发挥了任何作用; it seems the style object does this natively .

关于jquery - 是否可以使用 jQuery 删除内联样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2465158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com