前言
在很多網頁中我們經常會看到電影排行榜、時事熱點排行榜、熱銷圖書排行榜等等。今天這個案例就用jQuery實現一個熱銷圖書排行榜。So easy!!!
案例圖示
HTML<font color=red
簡單說一下頁面佈局:
主要部分就是五個 li標籤,標籤裏主要有一個 span標籤 和一個具有類選擇器 content 的 div標籤;類選擇器 content 作用是對 img標籤 和 p標籤 作樣式設置併到達左浮右浮的效果
<div class="box">
<h2>熱銷圖書排行榜</h2>
<ul>
<li>
<span>1</span>紅樓夢
<div class="content">
<img src="../program1/images/1.jpg" >
<p>我是第一本書的內容我是第一本書的內容我是第一本書的內容我是第一本書的內容</p>
</div>
</li>
<li>
<span>2</span>三國演義
<div class="content">
<img src="../program1/images/1.jpg" >
<p>我是第二本書的內容我是第二本書的內容我是第二本書的內容我是第二本書的內容</p>
</div>
</li>
<li>
<span>3</span>水滸傳
<div class="content">
<img src="../program1/images/1.jpg" >
<p>我是第三本書的內容我是第三本書的內容我是第三本書的內容我是第三本書的內容</p>
</div>
</li>
<li>
<span>4</span>西遊記
<div class="content">
<img src="../program1/images/1.jpg" >
<p>我是第四本書的內容我是第四本書的內容我是第四本書的內容我是第四本書的內容</p>
</div>
</li>
</ul>
</div>
CSS
簡單說一下頁面樣式佈局,這裏有幾點是需要大噶注意的吼
(1)ul>li:nth-child(-n+3) span :這句代碼實現的是 選取小於等於第三個 li標籤 的 span標籤 作相應的樣式.
(2)在上面說到了類選擇器 content 的作用是對 img標籤 和 p標籤 作樣式設置併到達左浮右浮的效果。特別要注意類選擇器content 要設置 overflow: hidden; 清除浮動;要設置 display: none; 隱藏,
(3)類選擇器 current 的作用是在 jQuery 中對已觸發事件的 li標籤 添加樣式,使類選擇器 content 所在的 div內容 顯示在瀏覽器上,所以設置 display: block;
<style>
* {
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
.box {
height: 400px;
width: 300px;
border: 2px solid #ccc;
margin: 20px auto;
}
.box h2 {
font-size: 20px;
line-height: 35px;
color: crimson;
padding-left: 5px;
border-bottom: 1px dashed #ccc;
}
ul>li {
padding: 5px;
border-bottom: 1px dashed #ccc;
}
ul>li:hover {
cursor: pointer;
}
ul>li:nth-child(-n+3) span {
background-color: crimson;
}
ul>li>span {
display: inline-block;
width: 20px;
height: 20px;
background-color: #ccc;
line-height: 20px;
text-align: center;
margin-right: 10px;
}
/* 父元素清除浮動 */
.content {
overflow: hidden;
padding: 5px;
display: none;
}
.content>img {
height: 80px;
float: left;
}
.content>p {
width: 130px;
float: right;
}
.current .content{
display: block;
}
</style>
jQuery核心代碼
1、 方法一
使用 mousemove和mouseout 對每個li標籤監聽移入移出事件。
觸發移入事件時添加類選擇器 current,觸發移出事件移除類選擇器 current
<script src="../jquery.js"></script>
<script>
$(function() {
//監聽li的移入事件
$("li").mousemove(function() {
$(this).addClass("current")
})
//監聽li的移出事件
$("li").mouseout(function() {
$(this).removeClass("current")
})
});
</script>
2、方法二
還可以使用 hover() 方法
<script src="../jquery.js"></script>
<script>
$(function() {
$("li").hover(function(){
$(this).addClass("current")
},function(){
$(this).removeClass("current")
})
});
</script>
如果大噶還不是很瞭解jQuery事件的使用,可以參考我寫的:(很詳細的知識總結) 一篇一萬字的jQuery事件知識總結