html代码:
<dl id="star">
<dt>推荐指数:</dt>
<dd>
<img src="images/icon1_1.png">
<img src="images/icon1_1.png">
<img src="images/icon1_1.png">
<img src="images/icon1_1.png">
<img src="images/icon1_1.png">
<input type="hidden" value="0" id="starnum" />
</dd>
</dl>
css代码:
body { font-size: 14px; color: #333; line-height: 1.8; }
img { display: block; }
#star dd img { float: left; padding: 5px; }
JavaScript代码:
var star = document.getElementById('star');
var starnum = document.getElementById('starnum');
var starimg = star.getElementsByTagName('img');
var len = starimg.length;
checkStar();
function checkStar() {
var val = starnum.value;
for (var i = 0; i < len; i++) {
if (i < val) {
starimg[i].setAttribute('src', 'images/icon1_2.png')
} else {
starimg[i].setAttribute('src', 'images/icon1_1.png')
}
}
}
for (var i = 0; i < len; i++) {
(function (ii) {
starimg[ii].onclick = function () {
var val = ii + 1;
for (var j = 0; j < len; j++) {
if (j < val) {
starimg[j].setAttribute('src', 'images/icon1_2.png');
} else {
starimg[j].setAttribute('src', 'images/icon1_1.png');
}
}
starnum.value = val;
};
}(i));
}
这里有个小难点关于click时 i 的取值问题,我是用了立即执行函数解决的,还可以用ES6的 let 处理,如下:
for (let i = 0; i < len; i++) {
starimg[i].onclick = function () {
var val = i + 1;
for (var j = 0; j < len; j++) {
if (j < val) {
starimg[j].setAttribute('src', 'images/icon1_2.png');
} else {
starimg[j].setAttribute('src', 'images/icon1_1.png');
}
}
starnum.value = val;
};
}
用jQuery改写就比较简单了,如下:
var $star = $("#star");
var $starnum = $("#starnum");
var $starimg = $star.find("img");
checkStar();
function checkStar(){
var val = $starnum.val();
var num = val-1;
$star.find("img:lt("+val+")").attr('src', 'images/icon1_2.png');
$star.find("img:gt("+num+")").attr('src', 'images/icon1_1.png');
}
$starimg.click(function() {
var num = $(this).index();
var val = num+1;
$star.find("img:lt("+val+")").attr('src', 'images/icon1_2.png');
$star.find("img:gt("+num+")").attr('src', 'images/icon1_1.png');
$star.find("#starnum").val(val);
});
用到了jQuery的‘:lt()’和‘:gt()’选择器。
两张小图在此
(完)