<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
img{
width: 100px;
height: 100px;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div>
<img src="1.jpg" alt="">
</div>
<table>
<tr>
<td></td>
<td><button value="up">向上</button></td>
<td></td>
</tr>
<tr>
<td><button value="left">向左</button></td>
<td></td>
<td><button value="right">向右</button></td>
</tr>
<tr>
<td></td>
<td><button value="down">向下</button></td>
<td></td>
</tr>
</table>
<script>
window.onload=function(){
var img = document.getElementsByTagName('img')[0];
var imgStyle = document.styleSheets[0].rules[1];//html中第一個css鏈接中的第二個css選擇器。
var imgTop = parseInt(imgStyle.style.top);
var imgLeft = parseInt(imgStyle.style.left);
var imgWidth = parseInt(imgStyle.style.width);
var imgHeight = parseInt(imgStyle.style.height);
//div的寬和高
var div = document.getElementsByTagName("div")[0];
var divStyle = document.styleSheets[0].rules[0];/html中第一個css鏈接中的第一個css選擇器盛正。
var divWidth = parseInt(divStyle.style.width);
var divHeight = parseInt(divStyle.style.height);
var button = document.getElementsByTagName("button");
//增加onclick事件
for(var i in button){
button[i].onclick = Move;
}
function Move(){
if(this.value == "up"){
if(imgTop == 0){
window.alert("已經(jīng)到達頂部拦赠,不能再向上移動了戚绕!");
}else{
imgTop = imgTop - 100;
}
}else if(this.value == "down"){
if((imgTop+imgHeight) == divHeight){
window.alert("已經(jīng)到達底部绸罗,不能再向下移動了箫爷!");
}else{
imgTop = imgTop + 100;
}
}else if(this.value == "left"){
if(imgLeft == 0){
window.alert("已經(jīng)到達左邊邊界,不能再向左移動了啊犬!");
}else{
imgLeft = imgLeft - 100;
}
}else if(this.value == "right"){
if((imgLeft+imgWidth) == divWidth){
window.alert("已經(jīng)到達右邊邊界灼擂,不能再向右移動了壁查!");
}else{
imgLeft = imgLeft + 100;
}
}
imgStyle.style.top = imgTop + "px";
imgStyle.style.left = imgLeft + "px";
}
}
</script>
</body>
</html>
** 初始效果預(yù)覽: **
捕獲.JPG
遇到的問題:
1.button[i].onclick = Move;此處不能用Move(),否則會調(diào)用Move()函數(shù)。
2.利用parseInt函數(shù)即可從"100px"中提取出數(shù)字100剔应。
- 有四個按鈕睡腿,onClick事件都增加的是Move()函數(shù),在其中使用this關(guān)鍵字即可獲得是哪個button調(diào)用的Move()峻贮,從而獲得value屬性席怪。而不用分別為每個按鈕增加一個單獨的函數(shù)。
4.使用document.styleSheets可訪問外部css纤控。