我需要使用javascript为圆形div设置边框颜色。用户选择两种颜色(例如红色和蓝色),边框在顶部变为红色,在底部变为蓝色。但是从边缘开始,边界应该从红色变为蓝色,反之亦然。换句话说,我需要为div的边框制作垂直渐变。 我可以用css制作它,但由于我不知道会选择哪种颜色,我需要javascript来为我做。
答案 0 :(得分:0)
一个纯粹的JavaScript解决方案来做到这一点。请注意,您需要执行一个时髦的getCssValuePrefix来确定哪个浏览器,从而调用相应的线性渐变函数。
var clicky = document.getElementById("changeButton"),
color1 = document.getElementById("color1"),
color2 = document.getElementById("color2"),
changeDiv = document.getElementsByClassName("foo")[0];
clicky.addEventListener("click", function(evt){
evt.preventDefault();
if (color1.value && color2.value) {
var myGradientString = getCssValuePrefix()+"linear-gradient("+color1.value+", "+color2.value+")";
changeDiv.style.background = myGradientString;
}
});
function getCssValuePrefix()
{
var rtrnVal = '';//default to standard syntax
var prefixes = ['-o-', '-ms-', '-moz-', '-webkit-'];
// Create a temporary DOM object for testing
var dom = document.createElement('div');
for (var i = 0; i < prefixes.length; i++)
{
// Attempt to set the style
dom.style.background = prefixes[i] + 'linear-gradient(#000000, #ffffff)';
// Detect if the style was successfully set
if (dom.style.background)
{
rtrnVal = prefixes[i];
}
}
dom = null;
delete dom;
return rtrnVal;
}
&#13;
.foo {
border: 1px solid black;
background-image: linear-gradient(red, blue);
}
label {
display: block;
}
&#13;
<div class="foo">
<p>Vivamus suscipit tortor eget felis porttitor volutpat. Sed porttitor lectus nibh. Donec rutrum congue leo eget malesuada. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur aliquet quam id dui posuere blandit. Cras ultricies ligula sed magna dictum porta. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Sed porttitor lectus nibh.</p>
</div>
<label for="color1">Color 1: <input type="text" name="color1" id="color1" value="#ee3"></label>
<label for="color2">Color 2: <input type="text" name="color2" id="color2" value="#336"></label>
<button id="changeButton">Make it so!</button>
&#13;
答案 1 :(得分:0)
我认为这是最适合你想要的解决方案:)我在Chrome,MF和Opera上尝过这种方式。将我的演示粘贴到空的html文件中。祝你好运!
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
#test
{
width: 300px;
height: 300px;
border-width: 3px;
border-style: solid;
border-image:
linear-gradient(blue, red) 1;
}
</style>
<body>
<input id="first" type="text">
<input id="second" type="text">
<input type="submit" onclick="changeColor()">
<div id="test"> </div>
<script>
var one = document.getElementById("first");
var two = document.getElementById("second");
var testDiv = document.getElementById("test");
function changeColor()
{
testDiv.style.borderImage = "linear-gradient(" + one.value + ", " + two.value + ") 1 ";
}
</script>
</body>
</html>