【问题标题】:How to calculate width and height of element in JQuery [closed]如何在JQuery中计算元素的宽度和高度[关闭]
【发布时间】:2015-11-27 03:04:44
【问题描述】:

我已经编写了这段代码来计算点击时现有元素的高度和宽度。这是正确的吗?

$('#submit').click(function(){
var width = ddbar.clientWidth;
var height = ddbar.clientHeight;
alert(width);
alert(height);
});

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

jQuery 让抓取元素的宽度和高度变得非常容易。

见:

假设dbbar是一个DOM元素,你需要做的就是:

    //get height of ddbar
    ddbar.height();

    //get width of ddbar
    ddbar.width();

根据您的要求将它们切换为内部/外部/等。

这应该很容易测试吧?

【讨论】:

    【解决方案2】:

    您应该使用这段代码,因为您使用的是 jQuery,以便它可以在浏览器兼容性方面发挥魔力:

    $('#submit').click(function(){
    var width = $(ddbar).width();
    var height = $(ddbar).height();
    alert(width);
    alert(height);
    });
    

    当然,jQuery 方式会慢一些:http://jsperf.com/jq-width-vs-client-width

    【讨论】:

      【解决方案3】:

      给你,

      http://jsfiddle.net/qR8Zw/1/

      $('#submit').click(function(){
          var width = $('#div').width();
          var height = $('#div').height();
          alert("Width" + width);
          alert("Height" +height);
      });
      

      干杯

      【讨论】:

        猜你喜欢
        • 2015-12-16
        • 2011-03-03
        • 1970-01-01
        • 1970-01-01
        • 2012-12-16
        • 2014-11-21
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        相关资源
        最近更新 更多