简体   繁体   中英

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:

  1. Fades out completely
  2. Updates with new content
  3. Positions to new screen coordinates
  4. Fades back in

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.

Here is where I'm at right now: 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.

That being said, change your moveDiv function to:

 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.

Fiddle.

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