How do I animate a clicked link before leaving page?

假装没事ソ 提交于 2019-12-08 05:15:36

问题


Here's what I want to achieve:

  1. When an HTML link is clicked, I want to animate it before leaving the page
  2. If the link is opened in a new window/tab, the animation should not take place

How on earth do I achieve this?


回答1:


You could use javascript

$(function(){
  $(".btn").bind("click",function(){
    $(this).animate({'left': '100px'}, 100, function(){
    window.location.href = index.html
  })
 })
})

But you'll have to stop the default action if your button is a link.




回答2:


You'll need to capture the click event, prevent the default action, do the animation, then load the new page.

If using jquery (Available as a jsfiddle):

$('a').click(function (event) {
  event.preventDefault();
  $(this).animate({
    //whatever
  }, function() {
    location.href = $(this).attr("href");
  });
});

Update: Here's the new jsfiddle that accounts for the situation mentioned in the comments, go there for the updated code. The trick is to look for the keypress of ctrl or command, and abort the newly defined animated click handler if either key is pressed.

Note: The window needs focus before it can detect a keypress, in jsfiddle, that means the frame needs focus before it'll work.



来源:https://stackoverflow.com/questions/9403585/how-do-i-animate-a-clicked-link-before-leaving-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!