简体   繁体   English

在锚点中使用#来实现javascript功能

[英]Using # in anchors for javascript functionality

Like most things in CSS, there are ways that work, and there are the right ways. 像CSS中的大多数东西一样,有一些方法可行,并且有正确的方法。 Unfortunately, I'm not so much of a CSS guru. 不幸的是,我不是一个CSS大师。

I set '#' I my hrefs for a number of things - for things like opening menus etc. 我设置'#'我的hrefs用于许多事情 - 例如打开菜单等。

However, I recently found a need to scroll smoothly to a place on the page. 但是,我最近发现需要顺利滚动到页面上的某个位置。 After some investigation, I came up with this code: 经过一番调查,我想出了这段代码:

$('a[href^="#"]').click(function (e) {
    e.preventDefault();

    $(".body-wrap").animate({
        scrollTop: $(this.hash).offset().top
    }, 300);
});

Nothing wrong with it - it works. 没有错 - 它有效。

However, it also causes conflict with every other '#' based href on the page that I use for other javascript triggers - specifically a[href^="#"] . 但是,它也会导致与我用于其他javascript触发器的页面上每个其他基于'#'的href冲突 - 特别a[href^="#"]

The question I have is, is there a better way to approach this that is still as generic? 我的问题是,有没有更好的方法来处理这仍然是通用的? For instance, you might say - don't need to assign # to all hrefs - I'm not sure what the impact might be, or there might be ways of adding to the selector above to make it more specific - such as, starts with #,but has other characters following. 例如,您可能会说 - 不需要为所有href分配# - 我不确定可能会产生什么影响,或者可能有一些方法可以添加到上面的选择器以使其更具体 - 例如,启动#,但是还有其他字符。

This kind of thing must challenge developers every day, so there must be preferred techniques, or patterns to deal with this cleanly. 这种事情必须每天挑战开发人员,所以必须有首选的技术或模式来干净地处理这个问题。

My preferred solution is to give them a class 我首选的解决方案是给他们上课

$(".scrollLink").on("click",function (e) {
  e.preventDefault();
  $(".body-wrap").animate({
    scrollTop: $(this.hash).offset().top
  }, 300);
});

The best practice is prefixing javascript specific classes with js- . 最佳实践是使用js-为javascript特定类添加前缀。

$(document).on('click', '.js-scroll-link', function(e) {
  e.preventDefault();

  $('.body-wrap').animate({
    scrollTop: $(this.hash).offset().top
  }, 300);
});

If you don't want/need to use classes, you can always check if this.hash is an empty string before animating. 如果您不想/不需要使用类,则可以在动画制作之前始终检查this.hash是否为空字符串。 In that case you will need to add empty/invisible <a id="top"></a> to the top of your page and set href to #top for your "smooth scroll links" which are meant to scroll to the top of page. 在这种情况下,您需要将空/不可见的<a id="top"></a>添加到页面顶部,并将href设置为#top以用于“平滑滚动链接”,这意味着滚动到顶部页面。

However using classes is preferable. 但是,使用类更可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM