переход css на элементе со значением, заданным с помощью javascript

#javascript #html #css

#javascript #HTML #css

Вопрос:

У меня есть таблица стилей с переходом, определенным для элемента, и некоторый html-код шаблона. Если я отложу настройку атрибута, который я хочу перевести в javascript, он будет работать нормально, но не без задержки. Я предполагаю, что это потому, что оба оцениваются одновременно. Есть ли лучший способ, которым я должен это делать?

 <html>
<head>
<style> 
div {
  width:0%;
  height: 100px;
  background: red;
  transition: width 2s;
}
</style>
<script>
/*
//this does work
setTimeout(()=>{
document.querySelector("div").style.width="100%";},1000);
*/

//this does not work
document.querySelector("div").style.width="200%";}
</script>
</head>
<body>

<h1>The transition Property</h1>

<p>Hover over the div element below, to see the transition effect:</p>
<div></div>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>

</body>
</html>  

Ответ №1:

Это не работает, потому что div не существует при запуске вашего кода. (Он выполняется перед отображением div.) Переместите скрипт в нижнюю часть тела или оберните его в прослушиватель событий, чтобы он запускался, когда ваша страница полностью загружена.

Также: у вас есть посторонний } в конце этой строки, который может вообще препятствовать его запуску.

 <html>

<head>
  <style>
    div {
      width: 0%;
      height: 100px;
      background: red;
      transition: width 2s;
    }
  </style>
  <script>
    /*
    //this does work
    setTimeout(()=>{
    document.querySelector("div").style.width="100%";},1000);
    */

    // wait for the page to load before running.
    window.addEventListener('load', () => {
      document.querySelector("div").style.width = "200%";
    })
    
  </script>
</head>

<body>

  <h1>The transition Property</h1>

  <p>Hover over the div element below, to see the transition effect:</p>
  <div></div>

  <p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>

</body>

</html>