利用 jQuery 實現(xiàn)多張圖片上下切換效果
1. 構(gòu)建 HTML 結(jié)構(gòu)首先,我們需要在 div 容器中添加一堆圖片。在本例中,我們使用 作為占位圖片。```html
1. 構(gòu)建 HTML 結(jié)構(gòu)
首先,我們需要在 div 容器中添加一堆圖片。在本例中,我們使用 作為占位圖片。
```html
```
2. 添加 CSS 樣式
為了實現(xiàn)圖片雜亂的效果,我們可以對 img 元素添加如下 CSS 樣式。這里使用的是 Chrome 瀏覽器的前綴,其他瀏覽器需要自行更改前綴。
```css
div img:nth-child(even) {
-webkit-transform: rotate(10deg);
margin-left: 5px;
}
div img:nth-child(3n) {
-webkit-transform: rotate(-15deg);
}
```
3. 設(shè)置 z-index
為了實現(xiàn)圖片的上下切換效果,我們需要為每個圖片設(shè)置不同的 z-index 值。
```javascript
var z 0;
$('pictures img').each(function() {
z ;
$(this).css('z-index', z);
});
```
4. 添加點擊事件
當用戶點擊圖片時,我們需要觸發(fā)圖片切換的動作。
```javascript
$('pictures').click(function() {
return swapFirstLast();
});
```
5. 實現(xiàn) swapFirstLast 函數(shù)
在 swapFirstLast 函數(shù)中,我們首先將當前最上層的圖片下移,然后將其 z-index 設(shè)置為最小值。接著,將其他圖片的 z-index 值加 1,實現(xiàn)上下切換的效果。
```javascript
function swapFirstLast() {
$('pictures img').each(function() {
if($(this).css('z-index') z) {
$(this).animate({
'top': '-' $(this).height() 'px'
}, 'slow', function() {
$(this).css('z-index', 1)
.animate({
'top': '0'
}, 'slow', function() {
});
});
} else {
$(this).css('z-index', parseInt($(this).css('z-index')) 1);
}
});
return false;
}
```
完整代碼
```html
/* CSS 代碼 */
```