我希望能够单击鼠标并将其保持在div内并移动其背景。在Google上搜索了很多内容,却没有找到我想要的。
好吧,让它起作用。我想我可以解决所有问题了:
最终的jQuery有界限
$(document).ready(function(){ var $bg = $('.bg-img'), elbounds = { w: parseInt($bg.width()), h: parseInt($bg.height()) }, bounds = {w: 2350 - elbounds.w, h: 1750 - elbounds.h}, origin = {x: 0, y: 0}, start = {x: 0, y: 0}, movecontinue = false; function move (e){ var inbounds = {x: false, y: false}, offset = { x: start.x - (origin.x - e.clientX), y: start.y - (origin.y - e.clientY) }; inbounds.x = offset.x < 0 && (offset.x * -1) < bounds.w; inbounds.y = offset.y < 0 && (offset.y * -1) < bounds.h; if (movecontinue && inbounds.x && inbounds.y) { start.x = offset.x; start.y = offset.y; $(this).css('background-position', start.x + 'px ' + start.y + 'px'); } origin.x = e.clientX; origin.y = e.clientY; e.stopPropagation(); return false; } function handle (e){ movecontinue = false; $bg.unbind('mousemove', move); if (e.type == 'mousedown') { origin.x = e.clientX; origin.y = e.clientY; movecontinue = true; $bg.bind('mousemove', move); } else { $(document.body).focus(); } e.stopPropagation(); return false; } function reset (){ start = {x: 0, y: 0}; $(this).css('backgroundPosition', '0 0'); } $bg.bind('mousedown mouseup mouseleave', handle); $bg.bind('dblclick', reset); });
原始答案
HTML
<div class="bg-img"></div>
CSS
div.bg-img { background-image: url(http://upload.wikimedia.org/wikipedia/commons/9/91/Flexopecten_ponticus_2008_G1.jpg); background-position: 0 0; background-repeat: no-repeat; background-color: blue; border: 1px solid #aaa; width: 250px; height: 250px; margin: 25px auto; }
jQuery
$(document).ready(function(){ var $bg = $('.bg-img'), origin = {x: 0, y: 0}, start = {x: 0, y: 0}, movecontinue = false; function move (e){ var moveby = { x: origin.x - e.clientX, y: origin.y - e.clientY }; if (movecontinue === true) { start.x = start.x - moveby.x; start.y = start.y - moveby.y; $(this).css('background-position', start.x + 'px ' + start.y + 'px'); } origin.x = e.clientX; origin.y = e.clientY; e.stopPropagation(); return false; } function handle (e){ movecontinue = false; $bg.unbind('mousemove', move); if (e.type == 'mousedown') { origin.x = e.clientX; origin.y = e.clientY; movecontinue = true; $bg.bind('mousemove', move); } else { $(document.body).focus(); } e.stopPropagation(); return false; } function reset (){ start = {x: 0, y: 0}; $(this).css('backgroundPosition', '0 0'); } $bg.bind('mousedown mouseup mouseleave', handle); $bg.bind('dblclick', reset); });