qiweile

事件的基本使用方式:

事件源.事件类型 = function(){事件触发后的操作};

点击事件:click;

在js中点击事件使用时前面要加on,为onclick;

例:点击btn按钮给box添加样式;

btn.onclick = funciton(){

  box.style.width = \'100px\';

  box.style.height = \'100px\';

  box.style.backgroundColor = \'red\';

};

移入移出事件

mouseover :鼠标移入事件;

 box.onmouseover = function(){

  this.style.backgroundColor = \'blue\';

}

mouseout :鼠标移出事件;

box.onmouseout = function(){

   this.style.backgroundColor = \'red\';

}

 

 

小例题;

  点击按钮实现页面变色的效果;

1、首先获取元素 btn 按钮 ;

2、事件绑定 btn.onclick = funciton(){};

3、在{}中写事件驱动程序;

  var btn = document.getElementById(\'btn\');

  var flag = true;  //为了实现上述效果我们采用一种简便方式;开闭原则;

  btn.onclick = function (){

    if(flag){//由于上面已经给flag赋值了true;所以此次判断可以进入;

      dcoument.body.className = \'black\';//给body赋值白色;

      btn.innerText = \'变成白色\';//给变按钮的内容;

      flag = false;//将flag设为false;让下次点击不能进入if循环,只能进入else;

    }else{

      document.body.className = \'white\';

      btn.innerText = \'变成黑色\';

      flag = true;//当页面设置为黑色时 给flag设置为true;让下次点击不能进入

            else只能进入if循环;

    }

  }

 

分类:

技术点:

相关文章: