【问题标题】:How can I change the style attributes of an HTML tag?如何更改 HTML 标签的样式属性?
【发布时间】:2012-07-06 08:35:20
【问题描述】:

考虑以下标签:

<div class="my_class" style="width: 453px; height: 604px;">
    // stuff
</div>

我想改成:

<div class="my_class" style="height: 453px; width: 604px;">
    // stuff
</div>

我需要使用 jquery 来执行此操作,我不一定知道 heightwidth 的值。我该怎么做呢?

【问题讨论】:

  • 您是否尝试将样式应用于具有特定类的所有divs?或者只是一个div,它也恰好有那个类名?
  • 我要做的就是将width 更改为height,并将height 更改为width。其他一切都保持不变。
  • 似乎有时计算机会“记住”旧的宽度和高度设置。这用于图像旋转功能。有没有办法“刷新缓存”,或者防止计算机记住以前的宽度和高度设置?

标签: jquery html tags


【解决方案1】:

这也将处理您想要一次对多个元素执行此操作的情况:

$('.my_class').each(function(){
    var $this = $(this);
    var oldWidth  = $this.css('width'),
        oldHeight = $this.css('height');
    $this.css({
        width: oldHeight,
        height: oldWidth
    });
});

【讨论】:

    【解决方案2】:

    尝试:

    var cls = $(".my_class"); 
    var h = cls.height();
    var w = cls.width();
    cls.css({"width":h,"height":w})
    

    【讨论】:

      【解决方案3】:

      交换宽度和高度:

          $('.my_class').css({
              width: $(this).height(),
              height: $(this).width()
          });
      

      jsFiddle example

      【讨论】:

        【解决方案4】:

        我认为这是最简单/最好的方法。

        http://jsfiddle.net/rp9jx/1/

        $('.my_class').removeAttr("style").attr({
          style: "height: 453px; width: 604px;"
        });
        

        【讨论】:

        • 最干净的方法,虽然我认为 prop (api.jquery.com/prop) 是现在推荐使用的 jQuery 方法来代替 attr。
        【解决方案5】:

        试试这个:

             $(function() {
             var Width  = $this.css('width'),
             height = $this.css('height');
             $(".my_class").width(width).height(height);
             });
        

             $(document).ready(function() {
             var Width  = $this.css('width'),
             height = $this.css('height');
             $(".my_class").width(604).height(height);
             }) ;
        

        【讨论】:

          猜你喜欢
          • 2011-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多