使用jquery插件删除内联样式

时间:2013-10-31 12:20:22

标签: javascript jquery jquery-plugins

我尝试使用this function

这是完整的html:

<html>
   <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>
     <div id="test" style="width:auto;max-width:150px;"></div>
     <script>
       (function($)
       {
           $.fn.removeStyle = function(style)
           {
               var search = new RegExp(style + '[^;]+;?', 'g');

               return this.each(function()
               {
                   $(this).attr('style', function(i, style)
                   {
                       return style.replace(search, '');
                   });
               });
           };
       }(jQuery));
       $(function(){
         $('#test').removeStyle('width');
       });
     </script>
   </body>
</html>

但我遇到了这个问题:

<div id="test" style="max-"></div>

6 个答案:

答案 0 :(得分:3)

以您发布的方式执行此操作:只需修改您的正则表达式即可与style匹配,但不匹配-style

以正确的方式做到:您只需使用:

$('#test').css('width', ''); 

Here是一个简单的小提琴,演示如何使用.css()删除背景。

答案 1 :(得分:2)

我认为您不想删除所有样式,只需 width:auto;

正则表达式匹配* width:*,因此它匹配max- width:150px;

请改为尝试:

var search = new RegExp('(^|;)' + style + '[^;]+;?', 'g');

这个正则表达式会期望a)字符串的开头或b)分号与字符串的另一部分匹配之前的分号。

另见:http://jsfiddle.net/P5dfz/

答案 2 :(得分:1)

你应该使用jQuery的.css()来操作样式:

$('#test').css("width","");

答案 3 :(得分:1)

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

           return this.each(function()
           { 
               $(this).css(style,'');
               /*$(this).attr('style', function(i, style)
               { 
                   return style.replace(search, '');
               });*/
           });
       };
   }(jQuery));
   $(function(){
     $('#test').removeStyle('width');
   });

修改了您的功能,请参阅小提琴http://jsfiddle.net/UA9CF/

答案 4 :(得分:0)

如果要删除完整的内联样式属性,则可以简单地使用它。

$('#test').removeAttr('style');

答案 5 :(得分:0)

但你问,如何删除内联样式,所以如果你想从给定范围内的某些元素中删除整个样式标记,你可以试试下面的内容:

说你的标记是这样的:

<div id="parent">
   <div style="background-color:red; width:100px; height:100px" >
      <div style="background-color:green; width:50px; height:50px" >
      </div>
   </div>
</div>
<div style="background-color:#CCC; width:50px; height:50px" >
</div>

并且您要删除div中ID为parent的元素的样式标记:

$('div',"#parent").removeAttr('style'); //$(selector, scope)

或者更简单的东西:

$("#parent").find('div,a').removeAttr('style'); //div,a or other element types