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

前端 未结 8 1206
遥遥无期
遥遥无期 2020-11-27 10:19

How do you find the current width of a

in a cross-browser compatible way without using a library like jQuery?

相关标签:
8条回答
  • 2020-11-27 10:53
    document.getElementById("mydiv").offsetWidth
    
    • element.offsetWidth (MDC)
    0 讨论(0)
  • 2020-11-27 10:53

    call below method on div or body tag onclick="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();
            }
    
    
        }
    
    0 讨论(0)
  • 2020-11-27 10:54

    Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

    var elem = document.getElementById("myDiv");
    if(elem) {
       var rect = elem.getBoundingClientRect();
       console.log(rect.width);  
    }
    
    0 讨论(0)
  • 2020-11-27 11:00

    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. For example: padding, paddingLeft, margin, border-top-left-radius and so on.

    0 讨论(0)
  • 2020-11-27 11:01

    You can also search the DOM using ClassName. 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.

    0 讨论(0)
  • 2020-11-27 11:03

    Actually, you don't have to use document.getElementById("mydiv") .
    You can simply use the id of the div, like:

    var w = mydiv.clientWidth;
    or
    var w = mydiv.offsetWidth;
    etc.

    0 讨论(0)
提交回复
热议问题