本文介绍了使用javascript定位字符串中的一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在$ < span>
标签中有这样的字符串:
hello,我想为每个字母执行一个代码(例如:隐藏,改变不透明度等)。如何使用JS / Jquery完成此操作而无需执行此操作:
< span> h< / span><跨度> e控制/跨度><跨度→1< /跨度><跨度→1< /跨度><跨度> O< /跨度>
解决方案
不,是。据我所知,不,每个字母周围的标签都是必要的,但是,是的,你可以用JavaScript来摆动它。这里有一些例子,使用这个概念为每个字符随机应用颜色和大小。
forEach
循环方法:
<跨度>你好< /跨度>
< script>
var span = document.querySelector('span')
var str_arr = span.innerHTML.split('')
span.innerHTML =''
var如果(ii var newSpan = document.createElement('span')
newSpan.style.color =#+((1 newSpan.style.fontSize =(Math.random()* (72-36)+36)+'px'
newSpan.innerHTML = str_arr [ii]
target.appendChild(newSpan)
setTimeout(function(){
crazy( ii + = 1,str_arr,target)
},1000)
}
}(ii,str_arr,span)
< / script>
Suppose I have this string:"hello" in a <span>
tag, and I want to execute a code for each letter (example: hide, change opacity, etc..). How can I make this with JS/Jquery without having to do this:
<span>h</span><span>e</span><span>l</span><span>l</span><span>o</span>
解决方案
No and yes. As far as I know, no, a span tag around each letter is necessary, but, yes, you can swing it in JavaScript. A couple examples here, using this concept to randomly apply a color and size to each character.
forEach
loop method:JSFiddle
<span>hello</span>
<script>
var span = document.querySelector('span')
var str = span.innerHTML
span.innerHTML = ''
str.split('').forEach(function (elem) {
var newSpan = document.createElement('span')
newSpan.style.color = "#"+((1<<24)*Math.random()|0).toString(16)
newSpan.style.fontSize = (Math.random() * (36 - 10) + 10) + 'px'
newSpan.innerHTML = elem
span.appendChild(newSpan)
})
</script>
setTimeout
method:JSFiddle
<span>hello</span>
<script>
var span = document.querySelector('span')
var str_arr = span.innerHTML.split('')
span.innerHTML = ''
var ii = 0
~function crazy(ii, str_arr, target) {
if ( ii < str_arr.length ) {
var newSpan = document.createElement('span')
newSpan.style.color = "#"+((1<<24)*Math.random()|0).toString(16)
newSpan.style.fontSize = (Math.random() * (72 - 36) + 36) + 'px'
newSpan.innerHTML = str_arr[ii]
target.appendChild(newSpan)
setTimeout(function () {
crazy(ii += 1, str_arr, target)
}, 1000)
}
}(ii, str_arr, span)
</script>
这篇关于使用javascript定位字符串中的一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!