js怎么改变图片位置,就是给一个坐标,图片到坐标位置

JavaScript016

js怎么改变图片位置,就是给一个坐标,图片到坐标位置,第1张

需要设置图片position:absolute这个CSS属性

然后就可以使用类似下面的方法

img假定为你要改的图片,可以使用

img=document.getElementById('图片id')得到,然后下面是位置

img.style.left="160px"

img.style.top="180px"

你说的这个功能可以实现,并不复杂,但是你说的如果是通过window.onresize时来触发函数,在检测屏幕的宽窄那样每个电脑的屏幕分辨率是不一样的,这样会容易出bug,不过如果限制的很小的范围则可以避免,希望你能更详细的描述你想要的效果,才能帮你写。

/**

* 简单自定义动画函数

* @param {objec} obj 一个元素对象

* @param {string} pos 表示移动到的目标地点

* @param {number} speed 速度大小,表示每秒移动的像素数,默认为1px/100ms

* @param {function} callback 动画执行完后调用的函数

* @return {[object]} 元素自身,方便链式写法

*/

function ani(obj, pos, speed, callback) {

/* 清除无用的定时器 */

if (obj.move) {

clearTimeout(obj.move)

}

obj.style.position = "absolute"

var speed = speed || 10,

x = parseInt(obj.style.left) || 0,

y = parseInt(obj.style.top) || 0

/* 初始化元素的相关属性值 */

if (!obj.x) {

obj.x = x

obj.y = y

obj.fx = x + pos[0]

obj.fy = y + pos[1]

}

/* 如果元素到达指定位置,则跳出并执行回调函数 */

if (x === (pos[0] + obj.x) &&y === (pos[1] + obj.y)) {

if (typeof callback === "function") {

callback()

}

obj.x = null

obj.y = null

obj.fx = null

obj.fy = null

return obj

}

/* 判断在水平方向上是应该往哪个方向移动 */

if (obj.x <obj.fx) {

if (x <obj.fx) {

obj.style.left = (x + speed) + "px"

}

} else {

if (x >obj.fx) {

obj.style.left = (x - speed) + "px"

}

}

/* 判断在垂直方向上是应该往哪个方向移动 */

if (obj.y <obj.fy) {

if (y <obj.fy) {

obj.style.top = (y + speed) + "px"

}

} else {

if (y >obj.fy) {

obj.style.top = (y - speed) + "px"

}

}

obj.move = setTimeout(function() {

ani(obj, pos, speed, callback)

}, 100)

}

window.onclick = function() {

ani($("#testAni")[0], [100, 0], 5, function() {

ani($("#testAni")[0], [-100, 0],null,function(){

alert("success")

})

})

}

可供参考