【问题标题】:Adding jQuery snippet to Drupal website将 jQuery 片段添加到 Drupal 网站
【发布时间】:2017-12-04 16:28:22
【问题描述】:

我正在尝试将以下 sn-p 添加到我的 Drupal 7 网站,但我不确定将其放在哪里。我真的只希望在一篇特定的博客文章中使用它,但如果它更容易应用于整个网站,那也很好。

$(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
       }, 1000);
       return false;
     }
   }
 });
});

Screenshot of website file structure

我以为我可以将它弹出到 common.js 文件中,但是当我这样做时,没有任何变化。这是代码:

$(document).ready(function(){
    // Remove scrollbar placed for non flicking carousel/no js version, show the thumbnails
    $("#carousels").css("height","auto").css("overflow","visible");
    $("#carousels .thumbs").css("display","block");

$(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
       }, 1000);
       return false;
     }
   }
 });
});
)};

关于如何添加此功能的任何想法?

【问题讨论】:

  • $(function() {}); function is eqaul to $(document).ready(function(){});`,所以你不需要创建另一个函数包装器。
  • 谢谢@ShaileshRathod 我删除了$(function() {});,但这个sn-p 仍然不起作用。还有其他想法吗?
  • 你有小提琴链接吗?所以我可以帮助你。
  • 刷新所有缓存(drush cc all)
  • @ShaileshRathod 我不确定如何将它添加到 js fiddle,因为它位于一个非常大的网站上,依赖于许多不同的文件......?我在 Code Pen 中测试了实际代码本身,它运行良好。这似乎是我错了。

标签: jquery drupal drupal-7


【解决方案1】:

您可以使用以下代码将 JS 文件添加到特定页面。所以想象一下你要添加代码的页面是www.yourwebsite.com/node/9

  function yourmodule_page_alter(&$page) {
    $pathElements = explode('/', current_path());

    if (count($pathElements) == 2 && $pathElements[0] == 'node' && $pathElements[1] == '9') {
      global $base_url;
      $path = $base_url . '/' . drupal_get_path('module','yourmodule');

      drupal_add_js(
        $path . "/includes/js/yourcustom.js",
        array(
          'type' => 'file',
          'scope' => 'header',
        )
      );
    }
  }

您可以找到有关hook_page_alter() here 的更多信息以及有关drupal_add_js() here 的更多信息。

【讨论】:

    猜你喜欢
    • 2012-04-04
    • 1970-01-01
    • 2015-02-19
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2017-07-22
    相关资源
    最近更新 更多