我有这样一句话:
<li id="menu-item-1542" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1542"><a href="contact-us/index.html">Contact </a></li>我需要用onclick替换href,但保留设计等,这是失败的,当鼠标在‘联系人’它没有显示小手创建的感觉,‘联系人’它只是文本,css也丢失了:
<li id="menu-item-1542" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1542" onclick="smoothScroll(document.getElementById('second'))">Contact</li>如何修复它?window.smoothScroll代码:
window.smoothScroll = function(target) {
var scrollContainer = target;
do { //find scroll container
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do { //find the top of target relatively to the container
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
scroll = function(c, a, b, i) {
i++; if (i > 30) return;
c.scrollTop = a + (b - a) / 30 * i;
setTimeout(function(){ scroll(c, a, b, i); }, 20);
}
// start scrolling
scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}发布于 2018-03-23 23:04:32
onclick only works one button标记
示例:单击按钮时执行JavaScript:
<button onclick="myFunction()">Click me</button>发布于 2018-03-23 23:12:27
你可以用多种方式来做,其中一些是我在下面创建的。通过保留href="#“和onclick事件锚标签,或者通过onClick直接给出到li标签的链接。为了验证onClick,我更改了"Contact“onclick的文本颜色。
<li id="menu-item-1542" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1542"
onclick="smoothScroll()"> Contact </li>
<li id="menu-item-1542" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1542">
<a href="#" onclick="smoothScroll()">Contact</a></li>
<script>
function smoothScroll (){
console.log('inside method');
document.getElementById('second');
document.getElementById("menu-item-1542").style.color = "red";
}
</script>发布于 2018-03-23 23:43:56
添加answer so可以将其标记为closed:
JS有点夸张,用纯HTML也能达到同样的效果:
<a href="#my-div">My link</a>
<div id="my-div">content</div>这将通过单击将页面跳转到#my-div
https://stackoverflow.com/questions/49452578
复制相似问题