在我的主页上,我想创建一个div,用户可以单击以更改背景颜色。要改变这种情况,我想使用这样的动画:点击后,新颜色应在鼠标点击周围展开圆形,并用新颜色填充整个div。
为此,我必须正确使用JavaScript,或者我只能使用CSS来执行此操作吗?当然我知道如何在EventListener
中设置JavaScript
,但我不知道如何用新颜色填充div圆形。你有什么想法怎么做?
答案 0 :(得分:6)
这可能就是你要找的东西:http://jsfiddle.net/F9pLC/
我们的想法是使用border-radius
创建一个圆圈,然后将其置于绝对位置。然后我们可以从鼠标坐标上增长它。
// You can modify this if you want
var START_RADIUS = 25;
$("#someText").click(function (e) {
// Get the width and the height
var width = $(this).width(),
height = $(this).height();
// Get the diagonal (this is what our circle needs to expand to)
var diag = Math.ceil(Math.sqrt(width * width + height * height)) * 2;
// Get the mouse coordinates
var pageX = e.pageX,
pageY = e.pageY;
// Create a circle
$('<div class="circle">').appendTo("#someText").css({
width: START_RADIUS * 2,
height: START_RADIUS * 2,
"border-radius": START_RADIUS,
top: pageY - START_RADIUS,
left: pageX - START_RADIUS,
"background-color": $("#newColor").val()
}).animate({
width: diag,
height: diag
}, {
step: function (now, fx) {
// This occurs every step of the animation
// Modify the radius so that it grows along with the width and height
if (fx.prop === "height") return;
$(this)
.css("top", pageY - START_RADIUS - now / 2)
.css("left", pageX - START_RADIUS - now / 2)
.css("border-radius", now / 2);
},
easing: "linear",
duration: 2000, // The number of milis to grow completely
done: function () {
// Remove the circle and change the background color
$("#someText").css("background-color", $(this).css("background-color")).css("z-index", "");
$(this).remove();
}
});
$("#someText").css("z-index", -3);
});
// So that when we click on the color input, it doesn't create a circle
$("#newColor").click(function(e) { e.stopPropagation(); });