Я нахожу, что довольно трудно следовать без воссоздания и увидеть, где эти цифры берутся. Однако недавно я сделал что-то очень похожее на jQuery для кого-то другого, кроме того, что он перемещает img внутри div. Вероятно, было бы не так много, чтобы переключить его, чтобы переместить фоновое изображение (хотя выяснение размеров bg-image было бы сложным - в этом случае вы могли бы лучше их кодировать).
HTML:
<div class="container"><img src="foo.jpg" class="draggable"/>
</div>
JQuery:
//for each item
$(".container").each(function(){
//get the container width
var conWidth = $(this).width();
//and its height
var imgHeight = $(this).find("img").height();
//get the nested img width
var conHeight = $(this).height();
//and its height
var imgWidth = $(this).find("img").width();
//figure out how much of the image is not visible horizontally
var excessWidth = imgWidth - conWidth;
//and how much is not visible vertically
var excessHeight = imgHeight - conHeight;
//how far is this container from the left of the page
var containerPositionLeft = this.offsetLeft;
//and from the top
var containerPositionTop = this.offsetTop;
//when moving mouse over container
$(this).mousemove(function(e){
//figure out how many pixels the mouse is from the left edge of the page
var mouseoffLeftPage = e.pageX;
//and how many from the top edge of the page
var mouseoffTopPage = e.pageY;
//figure out how many pixels the mouse is from the left edge of the page
var mouseoffLeftPx = mouseoffLeftPage - containerPositionLeft;
//and how many from the top edge of the page
var mouseoffTopPx = mouseoffTopPage - containerPositionTop;
//figure out the distance the mouse is from the left edge as a percentage (kind of - all the way to the right equals 1 not 100)
var mouseoffLeftPercent = mouseoffLeftPx/conWidth;
//do the same for height
var mouseoffTopPercent = mouseoffTopPx/conHeight;
//times the 'percentage' value by the amount of image hidden - so if your conatiner is 200px wide, your image 300px wide nd your mouse is half way across this value would be 0.5*100 which would give you 50 - which is exactly half the amount of image that is missing.
//note this gets set as a minus value as we will be using a minus number to shift the image around.
var setnewWidth = -(mouseoffLeftPercent * excessWidth);
//do the same for the height
var setnewHeight = -(mouseoffTopPercent * excessHeight);
//add the values as css (using transform(translate) as it's more performant and does subpixel rendering so looks smoother [or does it? it does in animations but seems as my js is not technically animating it it might not make a difference in that respect] - could set the top,left version as fallback for unsupporting browsers but ie9 supports transforms anyway so i dont care.)
$(this).find("img").css({"transform" : "translate("+ setnewWidth+"px ,"+setnewHeight+"px)" });
//$(this).find("img").css({"left" : setnewWidth+"px", "top" : setnewHeight+"px" });
});
});
не прямой ответ на то, что не работает в вашем коде, но показывает пример (с комментариями относительно того, что происходит), как это может быть сделано - обратите внимание, что моя версия не полагается на то, что вы знаете любую ширину или высоту объектов и можете запускать несколько элементов на одной странице - также ее не нужно размещать в самой верхней части страницы , Он предполагает, что изображение больше, чем его контейнер, хотя, если оно не больше, изображение просто перемещается внутри него. Вы могли бы уменьшить количество переменных, выполняя больше вычислений в строке, я просто хотел, чтобы было так же легко читать логику, насколько это возможно.
DEMO: http://codepen.io/chrisboon27/pen/BhkJq
Я добавил этот код на свой сайт, код выглядит хорошо, но изображение не перемещается – Chris
3 вещи: во-первых, похоже, что вы добавляете скрипт, прежде чем ссылаетесь на jQuery, поэтому код, вероятно, не работает в любом случае - вам нужно поставить код jQuery после ссылки на jQuery. Во-вторых, вы применяете css и нацеливаете jQuery на div с идентификатором #bg. Однако фон на вашей странице на самом деле находится на «теле», а не на div. Наконец, ваш #bg div пропускает закрывающий кавычек после имени идентификатора, и происходят другие странные вещи - он получает добавленную строку height: 20px, например, так что похоже, что есть проблема с вашим html. –
Отредактировано над комментарием - по какой-то причине я написал круглые скобки, когда имел в виду котировочный знак - извините, если это вызвало путаницу. –