这是我想要实现的一个例子:
[网站链接已删除]
但是如果你看一下源代码,它会有很多混乱的CSS代码。有没有办法用Javascript做到这一点? 先谢谢!
答案 0 :(得分:1)
这是一种只用HTML编写的方式:
<div id="wrap" >
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sollicitudin, felis nec lacinia egestas, metus sem tempor ligula, nec feugiat risus erat a ante. Vivamus a neque eu lorem pharetra vulputate ac id arcu. Nulla facilisi. Quisque porta purus id dolor sollicitudin ut interdum eros bibendum. Nunc dignissim velit vitae leo posuere vel tristique lacus bibendum. Nam suscipit elit magna. Cras odio ipsum, ultricies aliquet lacinia ac, tincidunt ut erat. In venenatis interdum mauris, a lobortis augue mattis vel. Donec sem urna, adipiscing laoreet consectetur nec, sodales id nibh. Integer gravida sem luctus nibh luctus tristique. In tempor adipiscing nisl. Proin consectetur, lorem eget sodales auctor, nulla quam condimentum tortor, sed fringilla massa neque non dolor.
</div>
JS:
var elem=document.getElementById("wrap");
var l=elem.innerHTML.length;
var newAns="";
for(var a=0;a<l;a++)
{
newAns+='<span onmouseover="change1(this)" onmouseout="change2(this)" >'+elem.innerHTML.charAt(a)+'</span>';
}
elem.innerHTML=newAns;
function change1(x)
{
x.style.color="yellow";
}
function change2(x)
{
x.style.color="black";
}
答案 1 :(得分:0)
我认为这应该有帮助,您可以实现悬停功能。
<script type="text/javascript">
var message = "The quick brown fox.";
var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue
for (var i = 0; i < message.length; i++)
document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");
</script>
答案 2 :(得分:0)
酷运动。我会这样使用jquery作为辅助:
编辑:你去悬停。没有测试它,所以检查语法错误以防万一:p<div id="divWithAString">a string</div>
(...)
<script type="text/javascript">
function CoolFunctionToGenerateHexColours(){
var color ="#", i ;
for(i=0;i<6;i++){
color += Math.floor(Math.random()*16).toString(16);
}
return color;
}
var s = $("#divWithAString").text();
$("#divWithAString").empty();
$(s).each(function(i,e){
var colorHex = CoolFunctionToGenerateHexColours();
var $htmlnode = $('<span >'+e+'</span>');
$htmlNode.hover(function(){
$(this).attr("style", "color: "+colorHex +";");
}, function(){
$(this).attr("style", "");
});
$("#divWithAString").append($htmlNode);
});
</script>