我正在尝试使用 Jquery/Javascript 来模仿损坏的打字机字体(因为我找不到)。但我想让它随机哪个字母被打破。我能够拆分我想要的 id 字符串,并使用我发现的一些代码来获得 0 和字符串总长度之间的随机数。我现在遇到的问题是用那个特定的 Angular 色做一些事情。我想将它向下或向上推几个像素。我试图给它上课,这样我就可以添加一些边距或填充,但它不起作用。所以我被困在现在的位置。
这是页面,我正在尝试对“关于”这个词进行操作:
http://www.franciscog.com/bs/about.php
这是脚本:
<script type="text/javascript">
function randomXToY(minVal,maxVal,floatVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
var str = $('#typehead').text();
var strcnt = str.length;
var exploded = str.split('');
var rdmltr =randomXToY(0,strcnt);
var theLetter = exploded[rdmltr];
theLetter.addClass("newClass");
var toffset = $('.newClass').offset();
alert(toffset.left + "," + toffset.top);
</script>
最佳答案
编辑:更新以确保匹配的字符不是空格字符,并添加了 @abelito 建议的一些样式。
这个怎么样:http://jsfiddle.net/cgXa3/4/
function randomXToY(minVal,maxVal,floatVal){
var randVal = minVal+(Math.random()*(maxVal-minVal));
return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
var exploded = $('#typehead').text().split('');
var rdmltr = randomXToY(0,exploded.length);
// Make sure we don't get a space character
while(exploded[rdmltr] == ' ') {
rdmltr = randomXToY(0,exploded.length);
}
// Wrap the letter with a span that has the newClass
// and update it in the array
exploded[rdmltr] = '<span class="newClass">' + exploded[rdmltr] + '</span>';
// Update the content
$('#typehead').html(exploded.join(''));
var toffset = $('.newClass').offset();
alert(toffset.left + "," + toffset.top);
更新:如果你想将它应用到多个:http://jsfiddle.net/cgXa3/5/
关于javascript - 选择字符串中的特定字符并使用 Jquery(视觉上)对其进行偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3277886/