如何使一个悬停功能,也是一个点击功能使用javascript

How to make a hover function ALSO a click function using javascript

本文关键字:功能 一个 javascript 悬停 何使一      更新时间:2023-09-26

我有一个工具提示,可以在下面看到,目前它显示的工具提示只在悬停,但我希望它显示的工具提示,当悬停和点击(触摸屏设备)有人能告诉我如何?

我JSFiddle

javascript代码

<script type="text/javascript">
$(function(){
  $("ul.thumb li").hover(function() {
  $(this)
    .css('z-index', '10')
    .find('img').addClass("hover")
    .stop()
    .animate({
       marginTop: '-150px',
       marginLeft: '-150px',
       top: '50%',
       left: '50%',
       width: '300px',
       height: '300px',
       padding: '20px'
     }, 200, function() {
        var $this = $(this),
        h = $this.height();
        $caption = $('<div class="caption">' + this.title  + '</div>')
            .css('top', h.toString() + 'px');
            $this.after($caption);
      }); 
   }, function() {
 $('.caption').remove();
 $(this)
.css('z-index', '0')
.find('img').removeClass("hover")
.stop()
.animate({
    marginTop: '0',
    marginLeft: '0',
    top: '0',
    left: '0',
    width: '200px',
    height: '200px',
    padding: '5px'
 }, 400);
});
});
</script>

你可以创建一个函数,我们叫它activate:

function activate(that) {
    //Your code here
}

,然后这样使用:

$("ul.thumb li").hover(function() {
    activate($(this));
});
$("ul.thumb li").click(function() {
    activate($(this));
});

注意,activate将保存在这些事件中需要处理的命令。另外,在activate中,尽量确保您使用的是that而不是this

首先,重构并重命名hover in/out函数:

function showTooltip(){
  $(this)
    .css('z-index', '10')
    .find('img').addClass("hover")
    .stop()
  // etc...
}
function hideTooltip(){
  $('.caption').remove();
  $(this)
    .css('z-index', '0')
    .find('img').removeClass("hover")
    .stop()
  // etc...
}

然后不使用hover简写,使用mouseentermouseleave事件来监听悬停:

$("ul.thumb li")
  .on('mouseenter', showTooltip)
  .on('mouseleave', hideTooltip);

如果你想显示触摸事件的工具提示,只需添加touchstart事件:我猜你想要点击打开和关闭工具提示。

$("ul.thumb li")
  .on('mouseenter touchstart', showTooltip)
  .on('mouseleave touchstart', hideTooltip);

你可以使用jQuery .on()方法绑定一个处理程序到多个事件…

首先你需要命名这两个函数。然后你可以这样使用.on():

$("ul.thumb li").on('mouseover touchstart', show);
$("ul.thumb li").on('mouseleave touchend', hide);
更新JSFiddle