写5个关于JS的高级特效代码
时间: 2024-05-13 10:20:38 浏览: 129
1. 点击按钮时,实现一个淡入淡出的动画效果:
```javascript
$(document).ready(function() {
$("button").click(function() {
$("div").fadeOut(1000).fadeIn(1000);
});
});
```
2. 实现一个无限滚动的图片轮播效果:
```javascript
$(document).ready(function() {
var i = 0;
var images = ["image1.jpg", "image2.jpg", "image3.jpg"];
setInterval(function() {
$("#slider").fadeOut(500, function() {
$(this).attr("src", images[i]).fadeIn(500);
});
i++;
if (i == images.length) {
i = 0;
}
}, 3000);
});
```
3. 实现一个全屏滚动效果,可以通过键盘或鼠标滚轮进行操作:
```javascript
$(document).ready(function() {
var current = 0;
var height = $(window).height();
var slides = $(".slide");
slides.eq(current).addClass("active");
$(document).on("keydown", function(e) {
if (e.keyCode == 38) {
current--;
if (current < 0) {
current = 0;
}
$("html, body").stop().animate({
scrollTop: current * height
}, 1000);
} else if (e.keyCode == 40) {
current++;
if (current >= slides.length) {
current = slides.length - 1;
}
$("html, body").stop().animate({
scrollTop: current * height
}, 1000);
}
});
$(window).on("mousewheel", function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
current--;
if (current < 0) {
current = 0;
}
$("html, body").stop().animate({
scrollTop: current * height
}, 1000);
} else {
current++;
if (current >= slides.length) {
current = slides.length - 1;
}
$("html, body").stop().animate({
scrollTop: current * height
}, 1000);
}
});
});
```
4. 实现一个可拖拽的元素效果,可以通过鼠标拖动改变元素的位置:
```javascript
$(document).ready(function() {
var dragging = false;
var target;
var offsetX, offsetY;
$("div").on("mousedown", function(e) {
dragging = true;
target = e.target;
offsetX = e.clientX - target.offsetLeft;
offsetY = e.clientY - target.offsetTop;
});
$("div").on("mousemove", function(e) {
if (dragging) {
target.style.left = e.clientX - offsetX + "px";
target.style.top = e.clientY - offsetY + "px";
}
});
$("div").on("mouseup", function() {
dragging = false;
});
});
```
5. 实现一个滚动时悬浮在页面顶部的导航栏效果:
```javascript
$(document).ready(function() {
var nav = $("nav");
var navTop = nav.offset().top;
$(window).on("scroll", function() {
if ($(window).scrollTop() >= navTop) {
nav.addClass("fixed");
} else {
nav.removeClass("fixed");
}
});
});
```
阅读全文