当 div 的高度达到特定像素时在 javascript 中调用函数



我想运行一个函数,当框宽度达到某个像素时运行,比如说 80px。 假设我想提醒"你好"并控制台.log"嘿"。我该如何才能做到这一点?而且我不能使用jQuery,所以请只是香草Javascript。

编辑:我想知道我是否可以插入类似函数的东西,该函数在redbox.style.width == "80px"时运行警报或控制台日志?

const redbox = document.querySelector("#redbox");
const coolbutton = document.querySelector("#coolbutton");
coolbutton.addEventListener("click", animator);
function animator() {
  if (redbox.style.width == "50px") {
   redbox.style.width = "100px";
   redbox.style.transition = "2s";
  } 
  else {
   redbox.style.width = "50px";
   redbox.style.transition = "2s";
  }
} 
#redbox {
  background: red;
  height: 50px;
  width: 50px;
}
<div id="redbox"></div>
<button id="coolbutton">click</button>

总而言之,在动画过渡期间没有事件处理程序(本机(。 但是,有一个用于过渡端的过渡端可以原生地与您的代码一起使用,但是由于您想在没有jquery的情况下在中间抓取其宽度,这使事情变得复杂。

我对请求动画帧几乎没有经验,但现在,在对您的代码进行了一些修改之后,这里有一个使用老式 setinterval 计时器的结构,应该可以让您开始您想要做的事情。

const redbox = document.querySelector("#redbox");
redbox.style.width = `50px`;
const coolbutton = document.querySelector("#coolbutton");
coolbutton.addEventListener("click", animator);
let toggle = true;
function animator() {
  let poller = setInterval(function(){
    let w = parseInt(redbox.style.width, 10);
    toggle ? w++ : w--;
    redbox.style.width = w + 'px';
    if (w == 100 || w == 50){          
      toggle = !toggle;
      clearInterval(poller);
    }
    if (w == 80)
      log(redbox.style.width);
  }, 20);
} 
function log(args){
  console.log(args);
}

小提琴手:https://jsfiddle.net/2mkxx6f0/4/

请检查代码,它不是80%,而是>80px

var redbox = document.querySelector("#redbox");
var coolbutton = document.querySelector("#coolbutton");
coolbutton.addEventListener("click", animator);
function animator() {
var a= Number("50");// increasing by 50 px
var b=Number(redbox.style.width.slice(0, -2));
  if (b <= 80) {
  var c=b+a+"px";
  
   redbox.style.width =c; 
   redbox.style.transition = "2s";
  } 
  else {
   alert("hii")
  }
} 
#redbox {
  background: red;
  height: 50px;
  width: 50px;
}
<body>
<div id="redbox"></div>
<button id="coolbutton">click</button>
</body>

最新更新