简体   繁体   中英

Javascript 100% width of an Element

Hi is there any way to check if an element like a progress bar has 100% width?

I've tried this but it does not work

let i = 0;
function start() {
    if (i == 0){
        i = 1;
        let elem = document.getElementById("myBar");
        let width = 10;
        let id =  setInterval(frame, 60);

        function frame() {
            if (elem.getAttribute("width") >= '100 %') {
                document.getElementsByTagName('form')[0].submit();
                clearInterval(id);
                i = 0;
            }
            else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }
}

Edit: html Code:

<div id ="myProgress">
   <div id="myBar"></div>
</div>

If you need raw property from style use element.style.width it will return string value (if setted through style attribute). If you need result value use window.getComputedStyle(element).width this will returns value in px

relates to: How to get an HTML element's style values in JavaScript?

Empty divs won't take space by default, you either need to add content inside it, or use CSS

Additionally if (elem.getAttribute("width") >= '100 %') should be if (width >= 100)

 function start() { let elem = document.getElementById("myBar"); let width = 10; let id = setInterval(frame, 60); function frame() { if (width >= 100) { // document.getElementsByTagName('form')[0].submit(); clearInterval(id); width = 10; } else { width++; elem.style.width = width + '%'; } } } start()
 #myProgress { background-color: #ccc; width: 100%; } #myBar { background-color: #00ff00; width: 0% } #myBar:after { content: '\200b'; }
 <div id="myProgress"> <div id="myBar"></div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM