使用JavaScript获取DIV的宽度和高度

11

我正在尝试获取用户更改后的div宽度和高度,并将该数字提交到另一个页面。但我似乎无法弄清如何获取宽度和高度。

<script>
$(function() {
  $( "#set div" ).draggable({ 
    stack: "#set div",
    preventCollision: true,
    containment: $('#main_content'),
      stop: function(event, ui) {
          var mydiv = document.getElementById("set");
          var pos_x = ui.offset.left;
          var pos_y = ui.offset.top;

          var width = mydiv.style.width;        ----THIS DOESN'T WORK
          var height = mydiv.style.height;      ----THIS DOESN'T WORK

          var window_width = window.innerWidth;
          var window_height = window.innerHeight;
          var need = ui.helper.data("need");

          console.log(pos_x);
          console.log(pos_y);
          console.log(width);
          console.log(window_width);
          console.log(need);

          //Do the ajax call to the server
          $.ajax({
              type: "POST",
              url: "updatecoords.php",
              data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height}
            }).done(function( msg ) {
              alert( "Data Saved: " + msg );
            });  
      }
  });
});
</script>

如何正确地完成这个任务?


不,那些行代码运行良好。 - Ohgodwhy
4个回答

24

使用ele.style.width获取元素宽度是非常错误的!!!

在原生JavaScript中,你可以通过两种方式获取元素的CSS:

标准方法

window.getComputedStyle(ele)
例如,
var ele = document.getElementById("content"), // Do not use #
    eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;

IE(IE 8及以下版本)

element.currentStyle
例如,
var ele = document.getElementById("content"), // Do not use #
    eleStyle = ele.currentStyle;
/* Below is the width of ele */
var eleWidth = eleStyle.width;

为什么不使用ele.style

ele.style只是获取ele元素的。如果你使用ele.style.width,你只能获得ele.style的宽度,并不能获取ele元素的真实宽度。

如果你已经这样做了:

ele.style.width = "55px"

当使用ele.style.width时,你会得到"55px"。如果没有,你将得到未定义(undefined)。

如何在jQuery中实现?

使用$ele.width()(如果您想要"精确"宽度,请使用$ele.outWidth()),jQuery已经为您完成了一切。


15

在普通的JavaScript中使用

var width = mydiv.offsetWidth;
var height = mydiv.offsetHeight;

这将给你数值,或者

var width = mydiv.offsetWidth + 'px';
var height = mydiv.offsetHeight + 'px';

如果您希望以“CSS”格式获取它们。


1
对于任何想知道的人, offsetWidth 是两者中更快的:https://jsperf.com/getcomputedstyle-vs-offsetwidth-offsetheight - Chris Dolphin

7

既然你正在使用jQuery,那么你可以这样做:

var width;

if (need == 1) {
   width = $("#web").width();
} else {
   width = $("#set").width();
}

在我的代码中,我有一个 var need。我该如何告诉脚本,如果 need = 1,则 var width= $("#web").width()。 - user2362601
我已经编辑答案,考虑到“需要”的值。 - Strille

1

由于您正在使用jQuery,您可能想了解以下内容:

$('#id').outerWidth() $('#id').outerWidth(true)

这些将非常有用。它允许您找到div的总宽度(填充,边框,宽度和(可选参数)边距)。

http://api.jquery.com/outerWidth/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接