簡體   English   中英

獲取div的寬度和高度,忽略“樣式”屬性

[英]Get width and height of div ignoring “style” attribute

我在沒有使用代碼生成的style屬性的情況下獲取div的原始寬度和高度時遇到問題。

這就是我解決的方法

    var currentWidth = $("#container").width();
    var currentHeight = $("#container").height();

    $("#container").removeAttr("style");


    var containerWidth = $("#container").width();
    var containerHeight = $("#container").height();

    $("#container").css("width", currentWidth, "height", currentHeight);


    $("#container").animate({
        width: containerWidth,
        height: containerHeight
    }, "slow"); 

這是很不好的編碼,並且不會動畫化高度。 我想有一種更簡單的方法可以解決此問題。 例如, $("#container").width(ignoring style attr);

編輯,更好的解釋:

在我的css文件中,容器的原始大小為500x500。 但是,當您單擊鏈接時,它更改為800x800(添加屬性樣式),現在當您單擊返回時,我希望將其更改回500x500,但是我希望代碼找出原始大小以便於更改。

更改#container的代碼:

    $("#container").animate({
        width: 1250,
        height: 600
    }, "slow");

提前致謝!

更新:

保持原始寬度和高度為min-widthmin-height即您的情況:

min-width: 500px;
min-height: 500px;

然后使用jQuery執行此操作:

$("#container").animate({
    width: "",
    height: ""
}, "slow"); 

工作小提琴

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
 <script type="text/javascript">
$(document).ready(function () {
    var curentDivWidth = 500;
    var curentDivHeight = 500;
    var clicked = false;
    $("#ClickMe").click(function () {
        if (!clicked) {
            $("#container").animate({
                width: 1250,
                height: 600
            }, "slow");
            clicked = true; return;
        }
        $("#container").animate({
            width: curentDivWidth,
            height: curentDivHeight
        }, "slow");
        clicked = false;
    });

});
  </script>
<title>example</title>
  </head>
  <body>
   <a href="javascript:void(0)" id="ClickMe" >click me </a>
  <div id="container" style="border:1px solid black" >
   the div 

  </div>
   </body>
   </html>

jsfiddle: http : //jsfiddle.net/seekpunk/JhzAD/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM