简体   繁体   中英

How do I add a paragraph's width with each click with Javascript?

I want to be able to add width to my paragraph with each click with Javascript. What am I doing wrong? Here is my code:

 let button = document.querySelector("button"); button.addEventListener("click",function(e) { let p = document.querySelector("p"); if(window.getComputedStyle(p).getPropertyValue("width")==="10px") { p.style.width = "10px"; p++; } else { console.log(false) } });
 p { box-shadow: 0 4px 8px rgb(0,0,0,0.4); height: 40px; width: 10px; display: block; }
 <button>click!</button> <p>my paragraph</p>

Your if condition is wrong, since you want to change the width with every click. Once you click the first time, you width will be 20px so the condition won't be met again. You want instead to check if the width is of a certain value.

Notice that I am checking var widthValue because it seems I cannot check the value of p.style.width

 var widthValue = 10; document.querySelector("button").addEventListener("click", function() { var p = document.querySelector("p"); if(widthValue < 100) { p.style.width = `${widthValue}px`; } widthValue += 10; });
 p { box-shadow: 0 4px 8px rgb(0,0,0,0.4); height: 40px; width: 10px; display: block; }
 <button>click!</button> <p>my paragraph</p>

This should create the desired effect that I think you were looking for. I got rid of the if statement and instead made it so whenever the button is clicked it increases the left margin by 1px. Changing the width wouldn't work because that changes the size of the paragraph block and not it's position.

 let button = document.querySelector("button"); let width = 0; button.onclick = function(){ width ++; var p = document.querySelector("p"); p.style = `margin-left:${width}px;`; };
 p { box-shadow: 0 4px 8px rgb(0,0,0,0.4); height: 40px; width: 10px; display: block; }
 <button>click!</button> <p>my paragraph</p>

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