0

サイズ変更時に、コードで最初の if ステートメントを実行する必要があります:「これは小さすぎると思います」。2 番目のサイズ変更では、最初の代替を実行する必要があります:「これは大きすぎると思います」。1回しか実行されませんが、変数の調整がローカルのみで、2回目は固執しないためですか?

var counter = 0;
function message() {
    if (counter == 0) {
        document.write("I think this is too small");
        counter = counter + 1;
    } else if (counter == 1) {
        document.write("I think this is too big");
        counter = counter + 1;
    } else {
        confirm("Third Time's a charm");
    }
}
window.addEventListener('resize', message, false);
   
<p>Text</p>

4

2 に答える 2

0

問題はdocument.write. 絶対に使用しないでくださいdocument.write。「ドキュメントに何か書きたいので、document.write完璧に見える」と思うかもしれません。間違っています。その名前にだまされました。仕様書にも恐ろしいと書​​いてある

何かを書きたいときはtextContent、 、innerHTMLまたは DOM メソッドを使用します。

var target = document.querySelector('p');
var counter = 0;
function message() {
  if (counter == 0) {
    target.textContent = "I think this is too small";
    counter = counter + 1;
  } else if (counter == 1) {
    target.textContent = "I think this is too big";
    counter = counter + 1;
  } else {
    target.textContent = "Third Time's a charm";
  }
}
window.addEventListener('resize', message, false);
<p>Text</p>

于 2016-06-04T19:06:00.177 に答える