简体   繁体   English

如何使用 Javascript 在每次点击时添加段落的宽度?

[英]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.我希望能够在每次点击 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.您的 if 条件是错误的,因为您想在每次点击时更改width Once you click the first time, you width will be 20px so the condition won't be met again.第一次单击后, width将为20px ,因此不会再次满足条件。 You want instead to check if the width is of a certain value.相反,您想检查width是否具有特定值。

Notice that I am checking var widthValue because it seems I cannot check the value of p.style.width请注意,我正在检查var widthValue因为我似乎无法检查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.我摆脱了 if 语句,而是这样做了,所以每当单击按钮时,它会将左边距增加 1px。 Changing the width wouldn't work because that changes the size of the paragraph block and not it's position.更改宽度不起作用,因为这会更改段落块的大小,而不是 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>

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

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