简体   繁体   中英

i want to change the box size how to use animate method?

i want to change the box size and how to use animate() method? I tried but it's not work... where is the problem??

<style>
.box {
 width: 200px;
 height: 200px;
 background-color: red;
  }
</style>

</head>
<body>
<div class="box"></div>
<script>
 const boxes = document.querySelector(".box");
 boxes.addEventListener("click", boxes1);
  function boxes1() {
    boxes.animate({
      width: "300px"
    });
  }
 /*boxes.click(function(){
  boxes.animate({width:"300"});
   }); << it also not work */
</script>

Here iam using Javascript and HTML to change the box width while click on it

  function change_width() { document.getElementById("box").style.width='300px'; } 
 #box { width: 200px; height: 200px; background-color: red; } 
 <html> <head> </head> <body> <div id="box" onclick="change_width()"></div> </body> </html> 

You can use the below code to animate the box on click

<html>
<head>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background-color: red;
      transition: width 300ms ease-in;
    }
  </style>
  <title>Title</title>
</head>
<body>
<div class="box"></div>
<script>
  const boxes = document.querySelector(".box");
  boxes.addEventListener("click", boxes1, false);

  function boxes1() {
    this.style.width = "300px";
  }
</script>
</body>
</html>

The animate() method is part of a library called jQuery which you need to include using <script></script> tags in your <head></head> to use.

In order to use jQuery methods, you need to apply them to a jQuery object. Here I have used $('.box') to select elements with the class box . In the function, you can then use $(this) (which is a jQuery object) to refer to the box clicked and animate it accordingly.

See example below:

 <html> <head> <!-- Include jQuery to use mthods such as .click & .animate --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> .box { width: 200px; height: 200px; background-color: red; } </style> </head> <body> <div class="box"></div> <script> $('.box').click(function(){ $(this).animate({width:"300"}); }); </script> </body> </html> 

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