Snipaste_2021-08-23_10-05-03.jpg

鼠标事件是HTMLDOM事件,鼠标事件大概有十种(见下图),主要谈一下onclick事件(点击事件)和onmouseover(鼠标移动到元素上触发事件)的妙用。
Snipaste_2021-08-23_10-16-22.jpg

onclick鼠标事件

介绍一下事件使用的注意点:
第一种情况:

HTML:

<div v-for="item in list" :key='item.id'>
    <div style="width:100px;height:100px;background-color: rgb(226, 185, 132);
               margin-left: 20px;" @click="clicked">
            {{item}}

</div>

js:

clicked(e){
 console.log(e);
},

打印结果:
Snipaste_2021-08-23_10-41-16.jpg

总结:当不传递参数的时候,默认是鼠标事件
第二种情况

HTML:

<div v-for="item in list" :key='item.id'>
        <div style="width:100px;height:100px;background-color: rgb(226, 185, 132);
                   margin-left: 20px;" @click="clicked(item)" @mouseover="mouseovered(item)">
                {{item}}
        </div>

js:

 clicked(item){
 console.log(item);
},

打印结果是data定义的数组list 的值
结论:当我们需要把dom里边的参数传递过来的时候,默认鼠标事件被覆盖
onmouseover事件函数也是和onclick一样的效果

下面是在开发uni-app时使用onclick的一个案例:
HTML代码:

<view style="display: flex;text-align: center;">
    <view v-for="(item,index) in list" :key="index"  style="margin-right: -4rpx;" >
        <view     @click="clicked(index,item)" :id='index' :class="[active==index?'item1':'']" 
                style="text-align: center; width: 90rpx;height: 120rpx;padding-top: 2rpx;
                        margin-right: 10rpx; margin-left:10rpx ; box-sizing: border-box;">
            <view style="font-family: Poppins;
                        font-style: normal;
                        font-weight: 500;
                        font-size: 30rpx;
                        color: #8894B1;">
                                
                <view :class="[active==index?'item2':'']"
                       class="weeke">
                    {{item.week}}
                </view >    
            </view>
            <view class="" style="font-family: Poppins;
                                    font-style: normal;
                                    font-weight: 600;
                                    font-size: 38rpx;
                                    color: #212525;">
                    <view :class="[active==index?'item2':'']">
                        {{item.data}}
                    </view >
            </view>                                                    
        </view>                
    </view>
</view>

js:

clicked(index,item){
    this.active=index
},

实现原理:通过点击,给不同的标签添加活跃类

实现效果截图:
Snipaste_2021-08-23_11-00-52.jpg


onmoveover事件

添加onmoveover事件,实现图片跟随鼠标移动

效果展示:

QQ图片20210823111101.png
angel.gif

HTML代码:

  <div class="box"  @mouseover="mouseovered">
    <img src="./assets/angel.gif" alt="" style="width:100px;height:90px">
  </div>

JS代码:

mouseovered(e){

  let img=document.querySelector("img")
  console.log(e,img)
  let x=e.pageX
  let y=e.pageY
  img.style.left=(x-50)+'px'
  img.style.top=(y-45)+'px'
}

实现原理:通过dom获取位置,通过onmoveover拿到鼠标当前的位置,把鼠标当前位置给图片。
注意:这里的图片一定要是且对定位,才能实现图片跟着鼠标移动。

Last modification:August 23rd, 2021 at 06:35 pm
如果觉得我的文章对你有用,请随意赞赏