Попытка завершить мою предварительную работу по написанию буткемпа с использованием getElementByID и addEventListener - PullRequest
0 голосов
/ 18 января 2020

Завтра я запускаю загрузочный лаг кодирования и смог завершить все свои предварительные рабочие модули, кроме этого.

Используя только html и Javascript, я должен попытаться получить эти кнопки работать, чтобы изменить этот объект в следующем коде:

    <!DOCTYPE html>
    <html>
    <head>
    <title>Jiggle Into JavaScript</title>
    <!-- <script type="text/javascript" 
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> -->
    </head>
    <body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"> . 
    </div>

    <button id="button1">Grow</button>
    <button id="button2">Blue</button>
    <button id="button3">Fade</button>
    <button id="button4">Reset</button>

    <script type="text/javascript" src="javascript.js"></script>

    </body>
    </html>

Вот где я нахожусь, и у меня, очевидно, возникают проблемы. Я чувствую, что знаю достаточно, чтобы создать беспорядок.

//the following is the fade function, 
//currently unattached to button:
//source: https://stackoverflow.com/questions/28662893/fade-in-and-fade-out-in-pure-javascript-without-jquery

var box = document.getElementById('box');

function fadeOut(elem, speed) {

  if (!elem.style.opacity) {
    elem.style.opacity = 1;
  } // end if

  var outInterval = setInterval(function() {
    elem.style.opacity -= 0.02;
    if (elem.style.opacity <= 0) {
      clearInterval(outInterval);
    } // end if
  }, speed / 50);
}

fadeOut(box, 2000);

// end fadeOut()
<!DOCTYPE html>
<html>

<head>

  <title>Jiggle Into JavaScript</title>

  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head>

<body>

  <p>Press the buttons to change the box!</p>

  <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"> .
  </div>

  <button id="growBtn">Grow</button>
  <button id="blueBtn">Blue</button>
  <button id="fadeBtn">Fade</button>
  <button id="resetBtn">Reset</button>

  <script type="text/javascript">
    document.getElementById("growBtn").addEventListener("click", function() {

      document.getElementById("box").style = "height:250px; width:250px;background-color: orange;margin: 25px";

    });

    document.getElementById("blueBtn").addEventListener("click", function() {

      document.getElementById("box").style = "height:150px; width:150px;background-color: blue;margin: 25px";

    });

    document.getElementById("fadeBtn").addEventListener("click", function() {

      document.getElementById("box").onclick.fadeOut();

    });

    document.getElementById("resetBtn").addEventListener("click", function() {

      document.getElementById("box").style = "height:150px; width:150px;background-color: orange;margin: 25px";

    });
  </script>

  <!-- Linking the JavaScript file -->

</body>

</html>

Я занимался исследованиями в течение нескольких дней, но нашел так много разных вариантов, и ни один из них не подходит.

Вот проблемы как они стоят сейчас:

  • Кнопка увеличения: Что ж, я могу увеличить его, но только один раз, не каждый раз, когда нажимается кнопка.

  • Синяя кнопка: Я могу сделать ее синей при нажатии кнопки, но размер изменится на исходный, если кнопка увеличения была нажата первой.

  • Кнопка Fade: Я нашел код для функции fadeOut на этом сайте (указан в коде), но я не знаю, как применить его к моему fadeBtn, поэтому окно исчезает сразу после открытия страницы. В настоящее время это единственный код в моем файле js.

  • Кнопка сброса: Это работает! Не уверен, что код, который я использовал, чтобы заставить его работать, является подходящим способом, но я возьму любую победу на этом этапе!

Я приму абсолютно любой совет / руководство / ссылки на Google любой готов поделиться, чтобы помочь мне! Я бы хотел запустить bootcamp на правой ноге и выяснить это.

Заранее спасибо!

Ответы [ 2 ]

1 голос
/ 18 января 2020

Во-первых, нет причины постоянно извлекать элемент на странице - назначьте его переменной один раз в начале, а затем ссылайтесь на эту переменную через ваши функции.

const box = document.getElementById('box');

Кроме того, при обновлении стилей элемента вы должны указывать определенный стиль c, который вы хотите изменить, а затем обновлять его напрямую

// Instead of this
document.getElementById("box").style = "height:250px; width:250px; 

// Do this ( Also applying the above tip )
const box = document.getElementById('box');

box.style.height = '250px';
box.style.width = '250px';

  1. Кнопка увеличения: я могу увеличить ее, но только один раз, не каждый раз, когда нажимается кнопка

Ваш код в настоящее время ничего не делает dynamici c - Вы просто устанавливаете его в жестко заданном размере. Вместо этого вы хотите получить текущий размер элемента, увеличить его, а затем присвоить это значение вашему элементу

. Вы можете использовать offsetHeight* 1024. * и offsetWidth для получения height / width элемента в виде числа для более простого добавления

let height = box.offsetHeight + 50; // Increasing the current size by 50
let width = box.offsetWidth + 50;

box.style.height = height + 'px'; // Assigning our increased size back to the box
box.style.width = width + 'px';

Синяя кнопка: я могу сделать ее синей при нажатии кнопки, но размер изменится на исходный, если кнопка увеличения была нажата первой.

Во всех ваших функциях вы перезаписываете все стили элемента box без причины. Если вы не перезаписываете стиль или не удаляете стиль, значения для каждого стиля останутся прежними. Когда вы обновляете backgroundColor, просто обновляйте backgroundColor.

box.style.backgroundColor = 'blue'; // This is all you need to change

Кнопка Fade: я нашел код для функции fadeOut на этом сайте (указан в коде), но я не знаю, как применить его к моему fadeBtn, поэтому окно исчезает сразу после открытия страница

Я немного озадачен тем, почему вы хотите, чтобы это применялось к блоку, как только страница загружается, несомненно, применяя этот стиль к блоку на Нажатие кнопки более уместно? Если это так, просто переместите вызов функции в обработчик click на кнопке

document.getElementById("fadeBtn").addEventListener("click", function() {
  fadeOut(box, 2000);
});

Кнопка сброса: это работает! Не уверен, что код, который я использовал, чтобы заставить его работать, является подходящим способом, но в этот момент я возьму любую победу!

Да, но вам не нужно сбросить margin, потому что вы его никогда не меняете.

Кроме того, поскольку ваша функция fadeOut работает в режиме setInterval до тех пор, пока непрозрачность не станет равной 0, нам нужен способ получить доступ и отменить этот интервал или иначе элемент будет продолжать исчезать - для этого я переместил объявление outInterval за пределы функции, поэтому вы можете вызвать clearInterval(outInterval) внутри функции сброса (это более заметно в фрагменте кода внизу)

// Reset 'Grow'
box.style.height = '150px';
box.style.width = '150px';

// Reset 'Blue'
box.style.backgroundColor = 'orange';

// Reset 'Fade'
clearInterval(outInterval);
box.style.opacity = 1;

Вот фрагмент кода с этими изменениями, чтобы вы могли посмотреть, как это работает - не стесняйтесь задавать любые вопросы, если вы не уверены в чем-то, или я пропустил детали

const box = document.getElementById('box');
let outInterval = null;

document.getElementById("growBtn").addEventListener("click", function() {
  let height = box.offsetHeight + 50;
  let width = box.offsetWidth + 50;
  
  box.style.height = height + 'px';
  box.style.width = width + 'px';
});

document.getElementById("blueBtn").addEventListener("click", function() {
  box.style.backgroundColor = 'blue';
});

document.getElementById("fadeBtn").addEventListener("click", function() {
  fadeOut(box, 2000);
});

document.getElementById("resetBtn").addEventListener("click", function() {
  // Reset 'Grow'
  box.style.height = '150px';
  box.style.width = '150px';
  
  // Reset 'Blue'
  box.style.backgroundColor = 'orange';
  
  // Reset 'Fade'
  clearInterval(outInterval);
  box.style.opacity = 1;
});

function fadeOut(elem, speed) {
  if (!elem.style.opacity) {
    elem.style.opacity = 1;
  } // end if

  outInterval = setInterval(function() {
    elem.style.opacity -= 0.02;
    if (elem.style.opacity <= 0) {
      clearInterval(outInterval);
    } // end if
  }, speed / 50);
};
<body>
  <p>Press the buttons to change the box!</p>

  <div id="box" class="box" style="height:150px; width:150px; background-color:orange; margin:25px"> . </div>

  <button id="growBtn">Grow</button>
  <button id="blueBtn">Blue</button>
  <button id="fadeBtn">Fade</button>
  <button id="resetBtn">Reset</button>
</body>
0 голосов
/ 18 января 2020

вот вам go Я объяснил, что и почему, но если у вас есть вопросы, просто задайте:

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Jiggle Into JavaScript</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <met charset="utf-8">
</head>
<body>
  <p>Press the buttons to change the box!</p>

  <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"> .
  </div>

  <button id="growBtn">Grow</button>
  <button id="blueBtn">Blue</button>
  <button id="fadeBtn">Fade</button>
  <button id="resetBtn">Reset</button>

  <script type="text/javascript">
    // The simples aproach would be to create global variable boxHeightAndWoxWidth and change it
    var boxHeightAndWidth = 150;
    document.getElementById("growBtn").addEventListener("click", function() {
      // Well my mate if you are tring to make box bigger each time then don't pass fixed height and width 
      // but make it bigger each time you pressed the button like so:
      boxHeightAndWidth += 10;
      // and we don't change color cuz why even?
      // document.getElementById("box").style = "height:" + boxHeightAndWidth +"px; width:" + boxHeightAndWidth + "px;background-color:orange; margin:25px";
      document.getElementById("box").style.height = boxHeightAndWidth + "px";
      document.getElementById("box").style.width = boxHeightAndWidth + "px";
      // jea we update this too so if you "faded" your box it will be seen again
      document.getElementById("box").style.opacity = "1";
    });

    document.getElementById("blueBtn").addEventListener("click", function() {
      // well of course it changes to orginal - you are passing fixed values which are lower then from growBtn
      // here we will use the global boxHeightAndWidth so it would stay the same
      // OR JUST DON'T CHANGE and change only required variables
      // document.getElementById("box").style = "height:150px; width:150px; background-color:blue; margin:25px";
      document.getElementById("box").style.backgroundColor = "blue";
      // jea we update this too so if you "faded" your box it will be seen again
      document.getElementById("box").style.opacity = "1";
    });


    // jea let's break this to pieces
    document.getElementById("fadeBtn").addEventListener("click", function() { // here you add event "onclick"

      // document.getElementById("box").onclick.fadeOut(); // here too but not in correct way so it doesn't even work
      // https://www.w3schools.com/jsref/event_onclick.asp - here, it's nicely exlpained
      // Correct way:
      // document.getElementById("box").onclick = function(){
      //   fadeOut();
      // };
      // but it's wrong too, because you would have to click twice to activate this script - if you wan't this behaviour the use "ondblclick"
      // so just pass this:
      // fadeOut();
      // but it's wrong too cuz this function requires variable to be passed
      // fadeOut(elem, speed) - elem - element to which apply fade and speed - speed of fade, so we will just copy the call from javascript.js:
      var box = document.getElementById('box');
      fadeOut(box, 2000);
      // and for explainations why it started without any action go to javascript.js
    });

    document.getElementById("resetBtn").addEventListener("click", function() {
      // This works because you reset styles to their start values. 
      document.getElementById("box").style = "height:150px; width:150px; background-color:orange; margin:25px";

    });
  </script>

  <!-- Linking the JavaScript file -->
  <script type="text/javascript" src="javascript.js"> </script>

</body>

</html>

И javascript. js:

//the following is the fade function,
   //currently unattached to button:
   //source: https://stackoverflow.com/questions/28662893/fade-in-and-fade-out-in-pure-javascript-without-jquery


   function fadeOut(elem, speed) {

   if (!elem.style.opacity) {
   elem.style.opacity = 1;
   } // end if

   var outInterval = setInterval(function () {
   elem.style.opacity -= 0.02;
   if (elem.style.opacity <= 0) {
       clearInterval(outInterval);
   } // end if
   }, speed / 50);
   }
   // cuz this calls the function just when the page loads so on the start of everything:
   // fadeOut(box, 2000);

   // end fadeOut()

Надеюсь, теперь ты все понимаешь <3. </p>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...