[英]What is the best way to achieve updating a DOM element with vanilla Javascript?
I would like to have aa div that does the following using vanilla javascript: 我想要一个使用香草javascript执行以下操作的div:
Cancelling fades mid way through also, so if a user clicks a button 20 times quickly, it doesn't fade in/fade out 20 times, just the most recent time. 取消也会在途中逐渐消失,因此,如果用户快速单击一个按钮20次,则不会在最近一次出现20次淡入/淡出。
Here is where I'm at right now: https://jsfiddle.net/d685Ledu/ 这是我现在所在的位置: https : //jsfiddle.net/d685Ledu/
<body>
<div id="wrapper">
<p>Content content</p>
</div>
<button id="button">click me</button>
</body>
<script type="text/javascript">
var wrapper = document.getElementById('wrapper');
var fadeSpeed = 0.01;
document.getElementById('button').addEventListener('click', function(){
fadeOut();
updateDiv();
moveDiv();
fadeIn();
});
function updateDiv() {
wrapper.innerHTML= '<div>lots</div><div>of</div><div>new</div><div>content</div>';
}
function moveDiv() {
wrapper.style.top = '100px';
wrapper.style.left = '100px';
}
function fadeIn() {
var opacity = 0;
function increase() {
opacity += fadeSpeed;
if (opacity >= 1){
wrapper.style.opacity = 1;
return true;
}
wrapper.style.opacity = opacity;
requestAnimationFrame(increase);
}
increase();
}
function fadeOut() {
var opacity = 1;
function decrease() {
opacity -= fadeSpeed;
if (opacity <= 0){
wrapper.style.opacity = 0;
return true;
}
wrapper.style.opacity = opacity;
requestAnimationFrame(decrease);
}
decrease();
}
</script>
What is the most idiomatic way to achieve this? 实现这一目标的最惯用的方法是什么?
You need to update margin-left
and margin-right
if you're simply trying to update that specific div. 如果您只是尝试更新特定的div,则需要更新margin-left
和margin-right
。
That being said, change your moveDiv
function to: 话虽如此,将您的moveDiv
函数更改为:
function moveDiv() {
wrapper.style["margin-left"]="100px";
wrapper.style["margin-top"]="100px";
}
Like I said in my second comment, I highly suggest you look into a framework. 就像我在第二条评论中所说的那样,我强烈建议您研究一下框架。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.