改变的随机字母的颜色在一个段落 [英] Change the color of random letters in a paragraph

查看:160
本文介绍了改变的随机字母的颜色在一个段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变一些随机字符颜色段落中的红色按钮上点击。请找我的code。我有这一些错误。

I want to change color of some random characters in a paragraph to red on a button click. Please find my code. I am having some errors in this.

$('input').click(function(){

   var para = $('#para');
   var position = Math.floor(Math.random()*100);
   var character = [];

   var i=0
   while ( i <= 30 )
   {
      character[i] = para.html().substr(position*(i+1), 1);
      i++;
   }

   $.each(character, function() {
     character.css('color','red');
   });

});

首先我创建了将包含从第30段随机字母数组
接下来,我用每()遍历每个数组中的元素应用CSS属性。
但是,一个错误在控制台窗口中弹出说对象有没有方法CSS

First of all I created an array which would contain 30 random letters from a paragraph Next I used each() to iterate over each of the elements in the array to apply the css property. But an error pops up in the console window saying object has no method 'css'

我究竟做错了什么?

推荐答案

首先,CSS方法只能在jQuery的对象。你有字符数组的字符串。 CSS方法不会对字符串工作。

First of all, CSS method will work only on jquery objects. You have strings in character array. css method won't work on strings.

其次,你的每一种方法是用错了。它应该是这样的。

Secondly, Your each method is written wrong. It should be like this

$.each(character, function(index, value) {
    // Do something
});

有关您的问题发言,以改变一些随机字符的颜色在您的字符串。这里是小提琴。尝试了这一点。

For your problem statement, to change color of some random characters in your string. Here is Fiddle. Try this out.

下面是code:

$('input').click(function(){

var para = $('#para');
var charArray = $('span', para);

// case: No span (Initial String)
if (charArray.length === 0) {
    var html = para.html();
    var newArr = [];
    var len = html.length;
    for (var i=0; i<len; i++) {
        newArr.push('<span>' + html[i] + '</span>');
    }
    html = newArr.join('');
    para.html(html);
    charArray = $('span', para);
}

// Reset all spans
$.each(charArray, function(i, value) {
    value.style.color = '';
});

var paralen = charArray.length;

for (var i=0; i<30; i++) {
    var pos = Math.floor(Math.random()*100);
    pos = pos % paralen;
    charArray[pos].style.color = 'red';
}

});

这篇关于改变的随机字母的颜色在一个段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆