javascript - 在字符串中的单词之前传递不间断空格

标签 javascript jquery

我有一个 JavaScript 变量,我需要在该变量下面的单词之前传递一些不间断的空格。

var str = "    Test";

我该如何实现这一目标?

最佳答案

你可以做这样的事情

  1. 使用 创建临时 div $("<div/>")
  2. 使用 html(str) 将 html 内容添加为字符串
  3. 现在要获取解码后的字符串,我们可以使用 text()

var str = "&nbsp;&nbsp;&nbsp;&nbsp;Test"
console.log($("<div/>").html(str).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

在纯 JavaScript 中,您可以使用 textarea ,

  1. 您可以使用 document.createElement('textarea') 创建文本区域
  2. 现在您可以使用innerHTML设置html内容
  3. 要检索解码的数据,您可以使用 ele.value

var str = "&nbsp;&nbsp;&nbsp;&nbsp;Test",
  ele = document.createElement('textarea');
ele.innerHTML = str;
console.log(ele.value);

我在您的插件代码中添加了一些细微的变化

/**
 * jquery.typist — animated text typing
 * @author Alexander Burtsev, http://burtsev.me, 2014—2015
 * @license MIT
 */
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else {
    factory(jQuery);
  }
}(function($) {
  'use strict';

  $.fn.typistInit = function() {
    return this.each(function() {
      if (!$(this).data('typist')) {
        new Typist(this);
      }
    });
  };

  $.fn.typist = function(opts) {
    return this.each(function() {
      new Typist(this, opts);
    });
  };

  $.fn.typistAdd = function(text, callback) {
    return this
      .typistInit()
      .each(function() {
        var self = $(this).data('typist');
        self.queue.push({
          text: text,
          callback: callback
        });
        self.type();
      });
  };

  $.fn.typistRemove = function(length, callback) {
    length = parseInt(length) || 0;

    return this
      .typistInit()
      .each(function() {
        var self = $(this).data('typist');
        self.queue.push({
          remove: length,
          callback: callback
        });
        self.type();
      });
  };

  $.fn.typistPause = function(delay, callback) {
    delay = parseInt(delay) || 0;

    return this
      .typistInit()
      .each(function() {
        var self = $(this).data('typist');
        self.queue.push({
          delay: delay,
          callback: callback
        });
        self.type();
      });
  };

  $.fn.typistStop = function() {
    return this
      .typistInit()
      .each(function() {
        var self = $(this).data('typist');
        self.queue.push({
          stop: true
        });
        self.type();
      });
  };

  /**
   * @class
   * @param {HTMLElement} element
   * @param {Object} [opts]
   * @param {String} [opts.text=''] Text for typing
   * @param {Number} [opts.speed=10] Typing speed (characters per second)
   * @param {Boolean} [opts.cursor=true] Shows blinking cursor
   * @param {Number} [opts.blinkSpeed=2] Blinking per second
   * @param {String} [opts.typeFrom='end'] Typing from start/end of element
   * @param {Object} [opts.cursorStyles] CSS properties for cursor element
   */
  function Typist(element, opts) {
    $.extend(this, {
      speed: 10, // characters per second
      text: '',
      cursor: true,
      blinkSpeed: 2, // blink per second
      typeFrom: 'end', // 'start', 'end'

      cursorStyles: {
        display: 'inline-block',
        fontStyle: 'normal',
        margin: '-2px 2px 0 2px'
      }
    }, opts || {});

    this._cursor = null;
    this._element = $(element);
    this._element.data('typist', this);
    this._container = null;

    this.queue = [];
    this.timer = null;
    this.delay = 1000 / this.speed;

    this.blinkTimer = null;
    this.blinkDelay = 1000 / this.blinkSpeed;

    if (this.text) {
      this.queue.push({
        text: this.text
      });
      this.type();
    }
  }

  Typist.prototype =
    /** @lends Typist */
    {
      /**
       * Adds blinking cursor into element
       */
      addCursor: function() {
        if (this._cursor) {
          clearInterval(this.blinkTimer);
          this._cursor
            .stop()
            .remove();
        }

        this._cursor = $('<span>|</span>')
          .css(this.cursorStyles)
          .insertAfter(this._container);

        this.cursorVisible = true;
        this.blinkTimer = setInterval($.proxy(function() {
          this.cursorVisible = !this.cursorVisible;
          this._cursor.animate({
            opacity: this.cursorVisible ? 1 : 0
          }, 100);
        }, this), this.blinkDelay);
      },

      /**
       * Triggers event
       * @param {String} event
       * @return {Typist}
       */
      fire: function(event) {
        this._element.trigger(event, this);
        return this;
      },

      /**
       * New line to <br> tag
       * @param {String} text
       * @return {String}
       */
      nl2br: function(text) {
        return text.replace(/\n/g, '<br>');
      },

      /**
       * <br> tag to new line
       * @param {String} html
       * @return {String}
       */
      br2nl: function(html) {
        return html.replace(/<br.*?>/g, '\n');
      },

      /**
       * Removes given number of characters
       * @param {Number} length
       * @param {Function} [callback]
       */
      remove: function(length, callback) {
        if (length <= 0) {
          callback();
          this.timer = null;
          return this
            .fire('end_remove.typist')
            .type();
        }

        var text = this._container.html();

        length--;
        text = this.br2nl(text);
        text = text.substr(0, text.length - 1);
        text = this.nl2br(text);

        this.timer = setTimeout($.proxy(function() {
          this._container.html(text);
          this.remove(length, callback);
        }, this), this.delay);
      },

      /**
       * Adds given text character by character
       * @param {String|Array} text
       */
      step: function(text, callback) {
        if (typeof text === 'string') {
          text = text.split('').map(function(v){return v.replace(' ','&nbsp;');});
        }

        if (!text.length) {
          callback();
          this.timer = null;
          return this
            .fire('end_type.typist')
            .type();
        }

        var character = text.shift();
        //character = $('<div>').text(character).html();
        character = this.nl2br(character);

        this.timer = setTimeout($.proxy(function() {
          this._container.html(this._container.html() + character);
          this.step(text, callback);
        }, this), this.delay);
      },

      /**
       * Stops all animations and removes cursor
       * @return {[type]} [description]
       */
      stop: function() {
        clearInterval(this.blinkTimer);
        this.blinkTimer = null;

        if (this._cursor) {
          this._cursor.remove();
          this._cursor = null;
        }

        clearTimeout(this.timer);
        this.timer = null;
      },

      /**
       * Gets and invokes tasks from queue
       */
      type: function() {
        if (this.timer) {
          return;
        }

        if (!this._container) {
          this._container = $('<span>');
          if (this.typeFrom === 'start') {
            this._element.prepend(this._container);
          } else {
            this._element.append(this._container);
          }
        }

        if (this.cursor) {
          this.addCursor();
        }

        var item = this.queue.shift() || {},
          callback = $.proxy(item.callback || $.noop, this);

        if (item.delay) {
          this
            .fire('start_pause.typist')
            .timer = setTimeout($.proxy(function() {
              callback();
              this.timer = null;
              this
                .fire('end_pause.typist')
                .type();
            }, this), item.delay);
          return;

        } else if (item.remove) {
          this
            .fire('start_remove.typist')
            .remove(item.remove, callback);
          return;

        } else if (item.stop) {
          this.stop();
          return;
        }

        if (!item.text) {
          return;
        }

        this
          .fire('start_type.typist')
          .step(item.text, callback);
      }
    };
}));

$('.typist')
  .typist({
    speed: 12,
    text: 'Hello!\n'
  })
  .typistAdd('It       working!');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="typist"></p>

关于javascript - 在字符串中的单词之前传递不间断空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31911739/

相关文章:

javascript - 当我们有 POST 表单数据时如何使用 javascript/jquery 禁用浏览器后退按钮

javascript - 如何将本地存储数组中的数据设置为输入类型="text"?

javascript - 通过 JS 中所需的组大小将一维数组转换为多维数组的更好方法

php - 针对 MySQL 完整性约束违规的 jQuery 警报 (Laravel)

javascript - 在 url 包含 2 个单独单词的页面上搜索 url

javascript - PHP 数组不通过循环显示所有值

jquery - 使用 jquery 附加到 <head> 时不应用 .less 样式,但 .css 有效

javascript - 使用 jQuery 删除不需要的行后如何重新编号列表?

Javascript:仅按单词随机播放

jquery - (jquery-ui) 设置 CSS 颜色的元素上的 toggleClass 颜色转换