我有一个带有悬停下拉菜单的菜单。在移动设备上,我想禁用
href
属性,以便单击链接不会重定向,而是打开下拉列表。我目前正在使用 removeAttribute()
来做到这一点。但问题是,如果用户在较小的窗口中使用该网站,这会触发移动版本,然后使窗口变大,我需要重新添加 href
。我可以使用 setAttribute()
但随后我必须跟踪链接才能将它们添加回来,我不认为这是最好的解决方案。有没有办法用js禁用href
属性?
尝试仅在较小的屏幕上阻止默认操作。
document.addEventListener('DOMContentLoaded', function() {
var menuLink = document.getElementById('dropdownMenuLink'); // The menu link ID
menuLink.addEventListener('click', function(event) {
// Check if the viewport width is less than or equal to 768px (Adjust to your use case)
if (window.innerWidth <= 768) {
// Prevent default link action
event.preventDefault();
// Display an alert
alert('Dropdown opening...'); // Placeholder action
// Here you would toggle your dropdown or execute any other mobile-specific action
}
// On larger screens, the default action (navigation) proceeds
});
});
<a href="#" class="menu-link" id="dropdownMenuLink">Menu Link</a>
您可以通过此事件监视屏幕大小调整...
window.visualViewport.onresize=function(e){
// And set conditions based on its height and/or width like this...
if(this.offsetWidth < 800){ // Or use offsetHeight.
a.href='javascript:SomeFunction();'; // If small make the href call a JS function.
} else {
a.href='https://somesite.com/'; // If big make it redirect to some link.
}
};