我尝试设置一个div,这样当拖动时,我的图像宽度会增长并缩小相同的距离。但是,如果我移动div 1px,我的图像宽度变化超过1px。
有什么建议吗?
function drag(el){
var dragging = dragging || false, x, handle_left, handle;
el.onmousedown = function(e){
e.preventDefault();
dragging = true;
handle = $(e.target);
x = e.clientX;
handle_left = handle.position().left;
window.onmousemove = function(e){
if(dragging == true){
var distance_w = e.clientX - x;
handle.css('left', (handle_left + distance_w)+'px');
$('.normal').css('width', $('.normal').width() + distance_w);
console.log(distance_w);
console.log($('.normal').width()+distance_w);
return false;
}
};
window.onmouseup = function(e){
dragging && (dragging = false);
};
};
};
var el = $('.btn');
for(var i = 0; i < el.length; i++){
drag(el[i]);
};
HTML
<div class="container">
<div class="wp_normal">
<div class="normal">
<img src="http://25.media.tumblr.com/284263a747fda7627c76920071ef580d/tumblr_mf8mf2FzZm1qm9rypo1_1280.jpg">
</div>
</div>
<div class="btn"></div>
</div>
CSS
.container{
position: relative;
width: 1024px;
margin: 0 auto;
}
.wp_normal{
position: absolute; z-index: 1;
left: 0; top: 0;
}
.normal{
position: relative;
width:500px; height: 280px;
margin: 0 auto;
overflow:hidden;
}
.normal img{
position:absolute;
width: 1024px; height: 280px;
}
.btn{
position: absolute; z-index: 3;
width: 100px; height: 100px;
background-color: red;
left: 450px;
}
答案 0 :(得分:1)
数学不好。每一步都调整了正常和应用的delta X的宽度。您需要使用基本宽度,就像使用handle_left一样。另外,不要忘记变量声明的var
- 如果你不这样做,它们将成为全局范围的一部分,并且它会让你更晚。
el.onmousedown = function(e){
e.preventDefault();
var dragging = true,
handle = $(e.target),
x = e.clientX,
handle_left = handle.position().left,
normalWidth = $('.normal').width(); // base width
window.onmousemove = function(e){
if(dragging == true){
var distance_w = e.clientX - x;
handle.css('left', (handle_left + distance_w)+'px');
// reused width at start and applied delta
$('.normal').css('width', normalWidth + distance_w);
// ... rest of code
答案 1 :(得分:0)
的 LIVE DEMO 强>
你的MATH中缺少很多东西
$(function(){
function drag(el){
var mDown = false,
x, // mouse X
handle_left,
handle,
handle_width2, /* missing this */
clickedAt, /* and this */
$normal, /* and this! */
normal_width; /* and this! */
el.onmousedown = function( e ) {
e.preventDefault();
mDown = true;
x = e.clientX;
handle = $(e.target);
handle_width2 = handle.width()/2;
$normal = handle.prev('div').find('.normal'); /* you were missing this */
normal_width = $normal.width(); /* and this */
handle_left = handle.position().left;
clickedAt = x-handle_left; /* gives the mouse position inside "handle" */
/* you'll have to add to this math the .normal offset().left */
window.onmousemove = function( e ) {
if(mDown){
x = e.clientX;
handle.css({left: x-clickedAt });
$normal.css({ width : handle.position().left + handle_width2 });
return false;
}
};
el.onmouseup = function(e){
mDown = false;
};
};
}
var el = $('.btn');
for(var i = 0; i < el.length; i++){
drag(el[i]);
}
});