我正在尝试制作一个基本的登陆页面,每次页面加载时都会随机化背景颜色,并且每次单击 svg 图标时也会发生变化。
到目前为止,这工作正常,但是是否也可以随机化图标的颜色,而不仅仅是白色?我在将 svg 的颜色属性集成到 javascript 时遇到问题。这是我当前正在使用的代码:
$(function() {
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
$("body").css({
backgroundColor: '#' + randomColor
});
$("#colorcode").text("#" + randomColor);
});
var safeColors = ['00', '33', '66', '99', 'cc', 'ff'];
var rand = function() {
return Math.floor(Math.random() * 6);
};
var randomColor = function() {
var r = safeColors[rand()];
var g = safeColors[rand()];
var b = safeColors[rand()];
return "#" + r + g + b;
};
$("body").css({
backgroundColor: '#' + randomColor
});
$(document).ready(function() {
$('#Layer_1').click(function() {
$('body').each(function() {
$(this).css('background', randomColor());
});
});
});
.cls-1 {
fill: #fff;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<div style="width:400px; position:absolute; left:50%; top:50%; margin:-200px 0 0 -200px; cursor: pointer">
<svg data-name="Layer 1" id="Layer_1" viewbox="0 0 400 400" xmlns="http://www.w3.org/2000/svg">
<title>Artboard 1</title>
<polygon class="cls-1" points="276 124 276 0 124 0 124 124 0 124 0 276 124 276 124 400 276 400 276 276 400 276 400 124 276 124"></polygon>
</svg>
非常感谢您的帮助。我对 Javascript 还很陌生,所以这对我来说是一个学习曲线。
最佳答案
您可以通过将 fill
CSS 属性应用于 svg 元素(在您的例子中为 polygon
)来更改 svg 的颜色
$('#Layer_1 polygon').css('fill', randomColor());
$(function() {
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
$("body").css({
backgroundColor: '#' + randomColor
});
$("#colorcode").text("#" + randomColor);
});
var safeColors = ['00', '33', '66', '99', 'cc', 'ff'];
var rand = function() {
return Math.floor(Math.random() * 6);
};
var randomColor = function() {
var r = safeColors[rand()];
var g = safeColors[rand()];
var b = safeColors[rand()];
return "#" + r + g + b;
};
$("body").css({
backgroundColor: '#' + randomColor
});
$(document).ready(function() {
$('#Layer_1').click(function() {
$('body').css('background', randomColor());
$('#Layer_1 polygon').css('fill', randomColor());
});
});
#svgdiv {
width: 400px;
position: absolute;
left: 50%;
top: 50%;
margin: -200px 0 0 -200px;
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="svgdiv">
<svg data-name="Layer 1" id="Layer_1" viewbox="0 0 400 400" xmlns="http://www.w3.org/2000/svg">
<polygon class="cls-1" points="276 124 276 0 124 0 124 124 0 124 0 276 124 276 124 400 276 400 276 276 400 276 400 124 276 124"></polygon>
</svg>
</div>
关于javascript - 如何随机化背景颜色和 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766398/