2012-07-06 52 views
3

考慮以下標籤:如何更改HTML標籤的樣式屬性?

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

我想將它更改爲:

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

我需要這樣做使用jQuery,我不一定會知道的heightwidth值。我會如何去做這件事?

+0

你們是不是要一個樣式應用到所有'div's有一定的階級?或者只是那個'div',也恰好有這個類名? – 2012-07-06 08:44:13

+0

我想要做的就是將'width'改爲'height',將'height'改爲'width'。其他一切都保持不變。 – 2012-07-06 08:47:53

+0

看來,有時計算機'記住'舊的寬度和高度設置。這用於圖像旋轉功能。有沒有辦法「沖洗緩存」,或者阻止計算機記住之前的寬度和高度設置? – 2012-07-06 08:59:43

回答

3

,你想同時做多個元素這也將處理情況:

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

精美的作品!非常感謝! – 2012-07-06 08:52:14

3

嘗試:

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

要交換的寬度和高度:

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

jsFiddle example

0

試試這個:

 $(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); 
    }) ; 
2

我覺得這是最簡單的/最佳途徑。

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

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

最簡潔的方法,儘管我認爲prop(http://api.jquery.com/prop/)是現在使用的推薦的jQuery方法來代替attr。 – lxalln 2012-07-06 09:29:18