向移动导航添加翻译类

时间:2018-11-14 20:41:44

标签: javascript jquery html css

我是javascript的新手,我不太清楚我应该在允许对网站进行翻译的类中添加的位置。

我有一个移动导航,当屏幕宽度为X较小时出现,并且在该导航中,我有许多指向网站其他部分的方向按钮,但是两个按钮(中英文翻译按钮)不起作用当被按下时。

我认为这是因为我没有在'is-mobile'类中添加'lang'类,但是我不知道如何执行此操作。

这是我的代码

(function($) {

  var $window = $(window),
    $body = $('body'),
    $header = $('#header'),
    $banner = $('#banner'),

    settings = {

      banner: {

        // Indicators (= the clickable dots at the bottom).
        indicators: true,

        // Transition speed (in ms)
        // For timing purposes only. It *must* match the transition speed of "#banner > article".
        speed: 1500,

        // Transition delay (in ms)
        delay: 5000,

        // Parallax intensity (between 0 and 1; higher = more intense, lower = less intense; 0 = off)
        parallax: 0.25

      }

    };

  /**
   * Applies parallax scrolling to an element's background image.
   * @return {jQuery} jQuery object.
   */
  $.fn._parallax = (browser.name == 'ie' || browser.name == 'edge' || browser.mobile) ? function() {
    return $(this)
  } : function(intensity) {

    var $window = $(window),
      $this = $(this);

    if (this.length == 0 || intensity === 0)
      return $this;

    if (this.length > 1) {

      for (var i = 0; i < this.length; i++)
        $(this[i])._parallax(intensity);

      return $this;

    }

    if (!intensity)
      intensity = 0.25;

    $this.each(function() {

      var $t = $(this),
        on, off;

      on = function() {

        $t.css('background-position', 'center 100%, center 100%, center 0px');

        $window
          .on('scroll._parallax', function() {

            var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);

            $t.css('background-position', 'center ' + (pos * (-1 * intensity)) + 'px');

          });

      };

      off = function() {

        $t
          .css('background-position', '');

        $window
          .off('scroll._parallax');

      };

      breakpoints.on('<=medium', off);
      breakpoints.on('>medium', on);

    });

    $window
      .off('load._parallax resize._parallax')
      .on('load._parallax resize._parallax', function() {
        $window.trigger('scroll');
      });

    return $(this);

  };


  /**
   * @return {jQuery} jQuery object.
   */
  $.fn._slider = function(options) {

    var $window = $(window),
      $this = $(this);

    if (this.length == 0)
      return $this;

    if (this.length > 1) {

      for (var i = 0; i < this.length; i++)
        $(this[i])._slider(options);

      return $this;

    }

    // Vars.
    var current = 0,
      pos = 0,
      lastPos = 0,
      slides = [],
      indicators = [],
      $indicators,
      $slides = $this.children('article'),
      intervalId,
      isLocked = false,
      i = 0;

    // Turn off indicators if we only have one slide.
    if ($slides.length == 1)
      options.indicators = false;

    // Functions.
    $this._switchTo = function(x, stop) {

      if (isLocked || pos == x)
        return;

      isLocked = true;

      if (stop)
        window.clearInterval(intervalId);

      // Update positions.
      lastPos = pos;
      pos = x;

      // Hide last slide.
      slides[lastPos].removeClass('top');

      if (options.indicators)
        indicators[lastPos].removeClass('visible');

      // Show new slide.
      slides[pos].addClass('visible').addClass('top');

      if (options.indicators)
        indicators[pos].addClass('visible');

      // Finish hiding last slide after a short delay.
      window.setTimeout(function() {

        slides[lastPos].addClass('instant').removeClass('visible');

        window.setTimeout(function() {

          slides[lastPos].removeClass('instant');
          isLocked = false;

        }, 100);

      }, options.speed);

    };

    // Indicators.
    if (options.indicators)
      $indicators = $('<ul class="indicators"></ul>').appendTo($this);

    // Slides.
    $slides
      .each(function() {

        var $slide = $(this),
          $img = $slide.find('img');

        // Slide.
        $slide
          .css('background-image', 'url("' + $img.attr('src') + '")')
          .css('background-position', ($slide.data('position') ? $slide.data('position') : 'center'));

        // Add to slides.
        slides.push($slide);

        // Indicators.
        if (options.indicators) {

          var $indicator_li = $('<li>' + i + '</li>').appendTo($indicators);

          // Indicator.
          $indicator_li
            .data('index', i)
            .on('click', function() {
              $this._switchTo($(this).data('index'), true);
            });

          // Add to indicators.
          indicators.push($indicator_li);

        }

        i++;

      })
      ._parallax(options.parallax);

    // Initial slide.
    slides[pos].addClass('visible').addClass('top');

    if (options.indicators)
      indicators[pos].addClass('visible');

    // Bail if we only have a single slide.
    if (slides.length == 1)
      return;

    // Main loop.
    intervalId = window.setInterval(function() {

      current++;

      if (current >= slides.length)
        current = 0;

      $this._switchTo(current);

    }, options.delay);

  };

  // Breakpoints.
  breakpoints({
    xlarge: ['1281px', '1680px'],
    large: ['981px', '1280px'],
    medium: ['737px', '980px'],
    small: ['481px', '736px'],
    xsmall: [null, '480px']
  });

  // Play initial animations on page load.
  $window.on('load', function() {
    window.setTimeout(function() {
      $body.removeClass('is-preload');
    }, 100);
  });

  // Mobile?
  if (browser.mobile)
    $body.addClass('is-mobile', 'tr');

  else {

    breakpoints.on('>medium', function() {
      $body.removeClass('is-mobile');
    });

    breakpoints.on('<=medium', function() {
      $body.addClass('is-mobile');



    });

  }


  // Dropdowns.
  $('#nav > ul').dropotron({
    alignment: 'center',
    hideDelay: 400
  });

  // Header.
  if ($banner.length > 0 &&
    $header.hasClass('alt')) {

    $window.on('resize', function() {
      $window.trigger('scroll');
    });

    $banner.scrollex({
      bottom: $header.outerHeight(),
      terminate: function() {
        $header.removeClass('alt');
      },
      enter: function() {
        $header.addClass('alt');
      },
      leave: function() {
        $header.removeClass('alt');
        $header.addClass('reveal');
      }
    });

  }

  // Banner.
  $banner._slider(settings.banner);

  // Off-Canvas Navigation.

  // Navigation Panel Toggle.
  $('<a href="#navPanel" class="navPanelToggle"></a>')
    .appendTo($header);

  // Navigation Panel.
  $(
      '<div id="navPanel">' +
      '<nav>' +
      $('#nav').navList() +
      '</nav>' +
      '<a href="#navPanel" class="close"></a>' +
      '</div>'
    )
    .appendTo($body)
    .panel({
      delay: 500,
      hideOnClick: true,
      hideOnSwipe: true,
      resetScroll: true,
      resetForms: true,
      side: 'right'
    });


  // onclick behavior
  $('.lang').click('touchstart', function() {
    var lang = $(this).attr('id'); // obtain language id

    // translate all translatable elements
    $('.tr').each(function(i) {
      $(this).text(aLangKeys[lang][$(this).attr('key')]);
    });

  });

  document.getElementById('ch').onclick = function() {
    var lang = $(this).attr('id'); // obtain language id

    // translate all translatable elements
    $('.tr').each(function(i) {
      $(this).text(aLangKeys[lang][$(this).attr('key')]);
    });


  }

  // preparing language file
  var aLangKeys = new Array();
  aLangKeys['en'] = new Array();
  aLangKeys['ch'] = new Array();

  aLangKeys['en']['home'] = 'Home';
  aLangKeys['en']['about'] = 'About Us';
  aLangKeys['en']['serv'] = 'Services';
  aLangKeys['en']['sem'] = 'Search Engine Marketing';
  aLangKeys['en']['webdev'] = 'Website Development';
  aLangKeys['en']['app'] = 'Mobile App Development';
  aLangKeys['en']['tbd'] = 'Technical Business Development';
  aLangKeys['en']['ourteam'] = 'Our Team';
  aLangKeys['en']['contactus'] = 'Contact Us';
  aLangKeys['en']['submit'] = 'Send Message';
  aLangKeys['en']['reset'] = 'Reset';



  aLangKeys['ch']['home'] = '首页';
  aLangKeys['ch']['about'] = '关于我们';
  aLangKeys['ch']['serv'] = '服务';
  aLangKeys['ch']['sem'] = '谷歌与雅虎推广';
  aLangKeys['ch']['webdev'] = '品牌网站建设';
  aLangKeys['ch']['app'] = 'APP 开发';
  aLangKeys['ch']['tbd'] = '加拿大工商业与市场拓展';
  aLangKeys['ch']['ourteam'] = '我们的团队';
  aLangKeys['ch']['contactus'] = '联络我们';
  aLangKeys['ch']['submit'] = '发留言';
  aLangKeys['ch']['reset'] = '重新';



})(jQuery);
<!-- Header -->
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<header id="header" class="alt">
  <h1>
    <a href="index.html"> <img src="images/Artboard%201.png" alt="logo" class="logo"> </a>
  </h1>
  <nav id="nav">
    <ul class="translate">
      <li><a href="index.html" key="home" class="tr">Home</a></li>
      <li><a href="AboutUs.html" key="about" class="tr">About Us</a></li>
      <li>
        <a href="#" class="submenu fa-angle-down tr" key="serv">Services</a>
        <ul>
          <li><a href="SEM.html" key="sem" class="tr">Search Engine Marketing</a></li>
          <li><a href="WebDev.html" key="webdev" class="tr">Website Development </a></li>
          <li><a href="AppDev.html" key="app" class="tr">App Development</a></li>
          <li><a href="Automation.html" key="tbd" class="tr">Technical Business Development</a></li>
        </ul>
      </li>
      <li><a href="ourteam.html" key="ourteam" class="tr">Our Team</a></li>
      <li><a href="#" id="en" class="button lang">English</a></li>
      <li><a href="#" id="ch" class="button lang">中文</a></li>
      <li><a href="#contact" class="button tr" key="contactus">Contact Us</a></li>
    </ul>

  </nav>

</header>

<!-- begin snippet: js hide: false console: true babel: false -->

这是JS代码的另一部分:

(function($) {

  /**
   * Generate an indented list of links from a nav. Meant for use with panel().
   * @return {jQuery} jQuery object.
   */
  $.fn.navList = function() {

    var $this = $(this);
    $a = $this.find('a'),
      b = [];

    $a.each(function() {

      var $this = $(this),
        indent = Math.max(0, $this.parents('li').length - 1),
        href = $this.attr('href'),
        target = $this.attr('target');

      b.push(
        '<a ' +
        'class="link depth-' + indent + '"' +
        ((typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
        ((typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
        '>' +
        '<span class="indent-' + indent + '"></span>' +
        $this.text() +
        '</a>'
      );

    });

    return b.join('');

  };

  /**
   * Panel-ify an element.
   * @param {object} userConfig User config.
   * @return {jQuery} jQuery object.
   */
  $.fn.panel = function(userConfig) {

    // No elements?
    if (this.length == 0)
      return $this;

    // Multiple elements?
    if (this.length > 1) {

      for (var i = 0; i < this.length; i++)
        $(this[i]).panel(userConfig);

      return $this;

    }

    // Vars.
    var $this = $(this),
      $body = $('body'),
      $window = $(window),
      id = $this.attr('id'),
      config;

    // Config.
    config = $.extend({

      // Delay.
      delay: 0,

      // Hide panel on link click.
      hideOnClick: false,

      // Hide panel on escape keypress.
      hideOnEscape: false,

      // Hide panel on swipe.
      hideOnSwipe: false,

      // Reset scroll position on hide.
      resetScroll: false,

      // Reset forms on hide.
      resetForms: false,

      // Side of viewport the panel will appear.
      side: null,

      // Target element for "class".
      target: $this,

      // Class to toggle.
      visibleClass: 'visible'

    }, userConfig);

    // Expand "target" if it's not a jQuery object already.
    if (typeof config.target != 'jQuery')
      config.target = $(config.target);

    // Panel.

    // Methods.
    $this._hide = function(event) {

      // Already hidden? Bail.
      if (!config.target.hasClass(config.visibleClass))
        return;

      // If an event was provided, cancel it.
      if (event) {

        event.preventDefault();
        event.stopPropagation();

      }

      // Hide.
      config.target.removeClass(config.visibleClass);

      // Post-hide stuff.
      window.setTimeout(function() {

        // Reset scroll position.
        if (config.resetScroll)
          $this.scrollTop(0);

        // Reset forms.
        if (config.resetForms)
          $this.find('form').each(function() {
            this.reset();
          });

      }, config.delay);

    };

    // Vendor fixes.
    $this
      .css('-ms-overflow-style', '-ms-autohiding-scrollbar')
      .css('-webkit-overflow-scrolling', 'touch');

    // Hide on click.
    if (config.hideOnClick) {

      $this.find('a')
        .css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)');

      $this
        .on('click', 'a', function(event) {

          var $a = $(this),
            href = $a.attr('href'),
            target = $a.attr('target');

          if (!href || href == '#' || href == '' || href == '#' + id)
            return;

          // Cancel original event.
          event.preventDefault();
          event.stopPropagation();

          // Hide panel.
          $this._hide();

          // Redirect to href.
          window.setTimeout(function() {

            if (target == '_blank')
              window.open(href);
            else
              window.location.href = href;

          }, config.delay + 10);

        });

    }

    // Event: Touch stuff.
    $this.on('touchstart', function(event) {

      $this.touchPosX = event.originalEvent.touches[0].pageX;
      $this.touchPosY = event.originalEvent.touches[0].pageY;

    })

    $this.on('touchmove', function(event) {

      if ($this.touchPosX === null ||
        $this.touchPosY === null)
        return;

      var diffX = $this.touchPosX - event.originalEvent.touches[0].pageX,
        diffY = $this.touchPosY - event.originalEvent.touches[0].pageY,
        th = $this.outerHeight(),
        ts = ($this.get(0).scrollHeight - $this.scrollTop());

      // Hide on swipe?
      if (config.hideOnSwipe) {

        var result = false,
          boundary = 20,
          delta = 50;

        switch (config.side) {

          case 'left':
            result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX > delta);
            break;

          case 'right':
            result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX < (-1 * delta));
            break;

          case 'top':
            result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY > delta);
            break;

          case 'bottom':
            result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY < (-1 * delta));
            break;

          default:
            break;

        }

        if (result) {

          $this.touchPosX = null;
          $this.touchPosY = null;
          $this._hide();

          return false;

        }

      }

      // Prevent vertical scrolling past the top or bottom.
      if (($this.scrollTop() < 0 && diffY < 0) ||
        (ts > (th - 2) && ts < (th + 2) && diffY > 0)) {

        event.preventDefault();
        event.stopPropagation();

      }

    });

    // Event: Prevent certain events inside the panel from bubbling.
    $this.on('click touchend touchstart touchmove', function(event) {
      event.stopPropagation();
    });

    // Event: Hide panel if a child anchor tag pointing to its ID is clicked.
    $this.on('click', 'a[href="#' + id + '"]', function(event) {

      event.preventDefault();
      event.stopPropagation();

      config.target.removeClass(config.visibleClass);

    });

    // Body.

    // Event: Hide panel on body click/tap.
    $body.on('click touchend', function(event) {
      $this._hide(event);
    });

    // Event: Toggle.
    $body.on('click', 'a[href="#' + id + '"]', function(event) {

      event.preventDefault();
      event.stopPropagation();

      config.target.toggleClass(config.visibleClass);

    });

    // Window.

    // Event: Hide on ESC.
    if (config.hideOnEscape)
      $window.on('keydown', function(event) {

        if (event.keyCode == 27)
          $this._hide(event);

      });

    return $this;

  };

  /**
   * Apply "placeholder" attribute polyfill to one or more forms.
   * @return {jQuery} jQuery object.
   */
  $.fn.placeholder = function() {

    // Browser natively supports placeholders? Bail.
    if (typeof(document.createElement('input')).placeholder != 'undefined')
      return $(this);

    // No elements?
    if (this.length == 0)
      return $this;

    // Multiple elements?
    if (this.length > 1) {

      for (var i = 0; i < this.length; i++)
        $(this[i]).placeholder();

      return $this;

    }

    // Vars.
    var $this = $(this);

    // Text, TextArea.
    $this.find('input[type=text],textarea')
      .each(function() {

        var i = $(this);

        if (i.val() == '' ||
          i.val() == i.attr('placeholder'))
          i
          .addClass('polyfill-placeholder')
          .val(i.attr('placeholder'));

      })
      .on('blur', function() {

        var i = $(this);

        if (i.attr('name').match(/-polyfill-field$/))
          return;

        if (i.val() == '')
          i
          .addClass('polyfill-placeholder')
          .val(i.attr('placeholder'));

      })
      .on('focus', function() {

        var i = $(this);

        if (i.attr('name').match(/-polyfill-field$/))
          return;

        if (i.val() == i.attr('placeholder'))
          i
          .removeClass('polyfill-placeholder')
          .val('');

      });

    // Password.
    $this.find('input[type=password]')
      .each(function() {

        var i = $(this);
        var x = $(
          $('<div>')
          .append(i.clone())
          .remove()
          .html()
          .replace(/type="password"/i, 'type="text"')
          .replace(/type=password/i, 'type=text')
        );

        if (i.attr('id') != '')
          x.attr('id', i.attr('id') + '-polyfill-field');

        if (i.attr('name') != '')
          x.attr('name', i.attr('name') + '-polyfill-field');

        x.addClass('polyfill-placeholder')
          .val(x.attr('placeholder')).insertAfter(i);

        if (i.val() == '')
          i.hide();
        else
          x.hide();

        i
          .on('blur', function(event) {

            event.preventDefault();

            var x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');

            if (i.val() == '') {

              i.hide();
              x.show();

            }

          });

        x
          .on('focus', function(event) {

            event.preventDefault();

            var i = x.parent().find('input[name=' + x.attr('name').replace('-polyfill-field', '') + ']');

            x.hide();

            i
              .show()
              .focus();

          })
          .on('keypress', function(event) {

            event.preventDefault();
            x.val('');

          });

      });

    // Events.
    $this
      .on('submit', function() {

        $this.find('input[type=text],input[type=password],textarea')
          .each(function(event) {

            var i = $(this);

            if (i.attr('name').match(/-polyfill-field$/))
              i.attr('name', '');

            if (i.val() == i.attr('placeholder')) {

              i.removeClass('polyfill-placeholder');
              i.val('');

            }

          });

      })
      .on('reset', function(event) {

        event.preventDefault();

        $this.find('select')
          .val($('option:first').val());

        $this.find('input,textarea')
          .each(function() {

            var i = $(this),
              x;

            i.removeClass('polyfill-placeholder');

            switch (this.type) {

              case 'submit':
              case 'reset':
                break;

              case 'password':
                i.val(i.attr('defaultValue'));

                x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');

                if (i.val() == '') {
                  i.hide();
                  x.show();
                } else {
                  i.show();
                  x.hide();
                }

                break;

              case 'checkbox':
              case 'radio':
                i.attr('checked', i.attr('defaultValue'));
                break;

              case 'text':
              case 'textarea':
                i.val(i.attr('defaultValue'));

                if (i.val() == '') {
                  i.addClass('polyfill-placeholder');
                  i.val(i.attr('placeholder'));
                }

                break;

              default:
                i.val(i.attr('defaultValue'));
                break;

            }
          });

      });

    return $this;

  };

  /**
   * Moves elements to/from the first positions of their respective parents.
   * @param {jQuery} $elements Elements (or selector) to move.
   * @param {bool} condition If true, moves elements to the top. Otherwise, moves elements back to their original locations.
   */
  $.prioritize = function($elements, condition) {

    var key = '__prioritize';

    // Expand $elements if it's not already a jQuery object.
    if (typeof $elements != 'jQuery')
      $elements = $($elements);

    // Step through elements.
    $elements.each(function() {

      var $e = $(this),
        $p,
        $parent = $e.parent();

      // No parent? Bail.
      if ($parent.length == 0)
        return;

      // Not moved? Move it.
      if (!$e.data(key)) {

        // Condition is false? Bail.
        if (!condition)
          return;

        // Get placeholder (which will serve as our point of reference for when this element needs to move back).
        $p = $e.prev();

        // Couldn't find anything? Means this element's already at the top, so bail.
        if ($p.length == 0)
          return;

        // Move element to top of parent.
        $e.prependTo($parent);

        // Mark element as moved.
        $e.data(key, $p);

      }

      // Moved already?
      else {

        // Condition is true? Bail.
        if (condition)
          return;

        $p = $e.data(key);

        // Move element back to its original location (using our placeholder).
        $e.insertAfter($p);

        // Unmark element as moved.
        $e.removeData(key);

      }

    });

  };


})(jQuery);

如果需要,这是我用于菜单下拉菜单的dropotron jquery文件的代码段。

我应该在哪里插入lang类,以便在移动导航中识别该类?谢谢!

1 个答案:

答案 0 :(得分:0)

我知道了!

我需要将类'tr'添加到:

'class =“ tr 链接深度-'+缩进+'”'+

只是忘了那个小东西...