简体   繁体   English

如何使用vanilla JavaScript找到div的宽度?

[英]How to find the width of a div using vanilla JavaScript?

如何在使用像jQuery这样的库的情况下以跨浏览器兼容的方式找到<div>的当前宽度?

document.getElementById("mydiv").offsetWidth

You can use clientWidth or offsetWidth Mozilla developer network reference 您可以使用clientWidthoffsetWidth Mozilla开发人员网络参考

It would be like: 这将是:

document.getElementById("yourDiv").clientWidth; // returns number, like 728

or with borders width : 或带边框宽度:

document.getElementById("yourDiv").offsetWidth; // 728 + borders width

All Answers are right, but i still want to give some other alternatives that may work. 所有答案都是正确的,但我仍然想提供其他一些可行的替代方案。

If you are looking for the assigned width (ignoring padding, margin and so on) you could use. 如果您正在寻找指定的宽度(忽略填充,边距等),您可以使用。

getComputedStyle(element).width; //returns value in px like "727.7px"

getComputedStyle allows you to access all styles of that elements. getComputedStyle允许您访问该元素的所有样式。 For example: padding, paddingLeft, margin, border-top-left-radius and so on. 例如:padding,paddingLeft,margin,border-top-left-radius等。

You can also search the DOM using ClassName. 您还可以使用ClassName搜索DOM。 For example: 例如:

document.getElementsByClassName("myDiv")

This will return an array. 这将返回一个数组。 If there is one particular property you are interested in. For example: 如果您有兴趣的某个特定属性。例如:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;

divWidth will now be equal to the the width of the first element in your div array. divWidth现在将等于div数组中第一个元素的宽度。

Actually, you don't have to use document.getElementById("mydiv") . 实际上,您不必使用document.getElementById("mydiv")
You can simply use the id of the div, like: 你可以简单地使用div的id,如:

var w = mydiv.clientWidth;
or 要么
var w = mydiv.offsetWidth;
etc. 等等

call below method on div or body tag onclick="show(event);" 在div或body标签上调用下面的方法onclick =“show(event);” function show(event) { function show(event){

        var x = event.clientX;
        var y = event.clientY;

        var ele = document.getElementById("tt");
        var width = ele.offsetWidth;
        var height = ele.offsetHeight;
        var half=(width/2);
       if(x>half)
        {
          //  alert('right click');
            gallery.next();
        }
        else
       {
           //   alert('left click');
            gallery.prev();
        }


    }

The correct way of getting computed style is waiting till page is rendered. 获取计算样式的正确方法是等待页面呈现。 It can be done in the following manner. 它可以通过以下方式完成。 Pay attention to timeout on getting auto values. 获取auto值时要注意超时。

function getStyleInfo() {
    setTimeout(function() {
        const style = window.getComputedStyle(document.getElementById('__root__'));
        if (style.height == 'auto') {
            getStyleInfo();
        }
        // IF we got here we can do actual business logic staff
        console.log(style.height, style.width);
    }, 100);
};

window.onload=function() { getStyleInfo(); };

If you use just 如果你只使用

window.onload=function() {
    var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}

you can get auto values for width and height because browsers does not render till full load is performed. 您可以获取宽度和高度的auto值,因为浏览器在执行完全加载之前不会渲染。

Another option is to use the getBoundingClientRect function. 另一种选择是使用getBoundingClientRect函数。 Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'. 请注意,如果元素的显示为“none”,则getBoundingClientRect将返回一个空矩形。

var elem = document.getElementById("myDiv");
if(elem) {
   var rect = elem.getBoundingClientRect();
   console.log(rect.width);  
}

如何用香草 javascript 确定一个<div>是可滚动的?</div><div id="text_translate"><p> 这个问题在这里( <a href="https://stackoverflow.com/questions/10948044/detect-if-the-div-have-scroll-bar-or-not/10948074" rel="nofollow noreferrer">检测 DIV 是否有滚动条[重复]</a> )和其他关于 SO 的问题的回答不准确。</p><p> 答案没有考虑到 div 的内容可能有一个float ,之后不会被清除。 div.clientHeight和div.scrollHeight不能用于检测滚动行为。 就像下面的例子: </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> window.addEventListener("load",function(){ var div = document.querySelector(".container"); document.querySelector(".clientHeight").innerHTML = div.clientHeight; document.querySelector(".scrollHeight").innerHTML = div.scrollHeight; });</pre><pre class="snippet-code-css lang-css prettyprint-override"> .container{ width: 50px; min-height: 20px; border: 1px solid red; }.floated{ float: left; }</pre><pre class="snippet-code-html lang-html prettyprint-override"> &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;clientHeight&lt;/th&gt; &lt;th&gt;scrollHeight&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="clientHeight"&gt;&lt;/td&gt; &lt;td class="scrollHeight"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class="container"&gt; &lt;div class="floated"&gt;Lorem ipsum dolor sit amet blah blah blah blah blah&lt;/div&gt; &lt;/div&gt;</pre></div></div><p></p><p> <a href="https://codepen.io/0t4k4r/pen/PooLygp" rel="nofollow noreferrer">密码笔</a></p></div> - How to determine with vanilla javascript that a <div> is scrollable?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取内容的宽度,而不是使用普通JavaScript的视口 - getting width of content, not viewport using vanilla JavaScript 使用香草 JavaScript 正确隐藏取消隐藏 Div - Hiding Unhiding Div Properly using vanilla JavaScript 使用香草 JavaScript 滚动时显示 div - Show div when scrolling using vanilla JavaScript 如何使用 Vanilla JavaScript 平滑过渡显示 div - How to display a div with a smooth transition with Vanilla JavaScript 如何在Vanilla JavaScript中执行$(&#39;。div a&#39;)? - How Can I Perform $('.div a') in Vanilla JavaScript? 如何用香草 javascript 确定一个<div>是可滚动的?</div><div id="text_translate"><p> 这个问题在这里( <a href="https://stackoverflow.com/questions/10948044/detect-if-the-div-have-scroll-bar-or-not/10948074" rel="nofollow noreferrer">检测 DIV 是否有滚动条[重复]</a> )和其他关于 SO 的问题的回答不准确。</p><p> 答案没有考虑到 div 的内容可能有一个float ,之后不会被清除。 div.clientHeight和div.scrollHeight不能用于检测滚动行为。 就像下面的例子: </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> window.addEventListener("load",function(){ var div = document.querySelector(".container"); document.querySelector(".clientHeight").innerHTML = div.clientHeight; document.querySelector(".scrollHeight").innerHTML = div.scrollHeight; });</pre><pre class="snippet-code-css lang-css prettyprint-override"> .container{ width: 50px; min-height: 20px; border: 1px solid red; }.floated{ float: left; }</pre><pre class="snippet-code-html lang-html prettyprint-override"> &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;clientHeight&lt;/th&gt; &lt;th&gt;scrollHeight&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="clientHeight"&gt;&lt;/td&gt; &lt;td class="scrollHeight"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class="container"&gt; &lt;div class="floated"&gt;Lorem ipsum dolor sit amet blah blah blah blah blah&lt;/div&gt; &lt;/div&gt;</pre></div></div><p></p><p> <a href="https://codepen.io/0t4k4r/pen/PooLygp" rel="nofollow noreferrer">密码笔</a></p></div> - How to determine with vanilla javascript that a <div> is scrollable? 如何找到原生 JavaScript 函数的实现代码 - How to find the implementation code of a vanilla JavaScript function 如何使用JQuery在另一个div中找到div的宽度 - How to find width of div inside another div using JQuery 如何使用 Javascript 查找 Masterpage 的高度和宽度 - How to find Masterpage height and width using Javascript 使用Vanilla JavaScript将元素高度设置为等于宽度 - Set element height equal to width using Vanilla javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM