javascript - 一起使用 <a href> 链接和 <onclick> 功能

标签 javascript jquery html css

如何使这个标签与 href 和 onClick 功能一起使用? (onClick 应该先运行然后 href)

版本 1

<a href="#" id="myHref">Click me</a>

$("#myHref").on('click', function() {
    document.getElementById(".myDiv").style.flexGrow = "5";
     window.location = "http://www.google.com";

});

版本 2

 <a href="http://www.google.com" onclick="return myFunction();">Link</a>

function myFunction() {
    document.getElementById(".myDiv").style.flexGrow = "5"; 
}

最佳答案

您需要取消点击,调用您的动画,然后添加延迟以跟随链接。

$("#myHref").on('click', function(evt) {
    evt.preventDefault(); //cancel the default click action
    document.getElementById(".myDiv").style.flexGrow = "5";
    var url = this.href;  //get the href of the clicked link
    window.setTimeout( function () {  //delay setting the location
        window.location.href = url;
    }, 5000); //number of milliseconds to wait
});

setTimeout 将允许动画发生。根据需要调整时间。

关于javascript - 一起使用 <a href> 链接和 <onclick> 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34888094/

相关文章:

javascript - 使用js函数document.appendchild时有没有办法避免浏览器重绘?

javascript - rxJs 过滤器列表,具有基于 angular4 中发出的值的去抖功能

javascript - 状态完成时的中止间隔 Javascript

javascript - 如何让我的结果在 javascript 中正确相加

HTML5 拖放上传

python - BeautifulSoup:不要在重要的地方添加空格,在不重要的地方删除它们

javascript - 如何使用 ES6 导入插件? (获取引用错误 : Plugin is not defined)

javascript - jQuery 对包含 div 和按钮的不同绑定(bind)

javascript - 使用ajax上传图像仅适用于png

javascript - 如果在某个网页上并离开另一个特定网页则运行脚本