javascript - 分离 javascript 函数的最佳方法是什么?

标签 javascript jquery

我有两个互相冲突的 JavaScript 文件。一种是打开模式并使用类似 <a href="#modal" data-toggle="modal">open modal</a> 的链接,然后用 id="modal" 打开模式。但另一个脚本是为了平滑滚动,它从 url (I'd like to keep that part!) 中删除 anchor 。但添加平滑滚动脚本后,模态不起作用。我有什么办法可以解决这个问题吗?

modal.js:

$(".modal-wide").on("show.modal", function() {

  var height = $(window).height() - 200;
  $(this).find(".modal-body").css("max-height", height);
});
$('a[data-toggle="modal"]').bind('click',function(){
  $('.modal').modal('hide');
});

滚动.js:

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});

scroll.js 来源:https://css-tricks.com/snippets/jquery/smooth-scrolling/

最佳答案

尝试将特定的 href 标签添加到平滑滚动功能的非选择器中。

$('a[href*="#"]:not([href="#"]):not([href="#modal"])').click(function() 

这是一个 fiddle ,显示 smoothscroll 仅适用于平滑滚动 div,它应该保留您的模态功能。

https://jsfiddle.net/bryangators/wjgu1vL9/

关于javascript - 分离 javascript 函数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43006091/

相关文章:

javascript - POST 请求作为 GET 传递的问题

jQuery 存储对 $(this) 的引用

javascript - CSS - 是否可以使用纯 CSS 卡住 html 表格顶部的标题以防止滚动?

javascript - 单击时如何添加/删除属性

javascript - 删除所有元素的 Firebase 查询

javascript倒数计时器删除小时分钟秒..到期后

javascript - div变换后定位内容

javascript - 如何在一定高度后固定滚动 div 并在到达其他 div 后停止?

javascript - 使用 jQuery 重定向到另一个页面在 IE 中有效,但在 Firefox、Safari 中无效

javascript - 防止 body 在鼠标滚轮上滚动,但不是文本区域