[英]overflow in div for image drag and drop
我正在使用javascript和html5將圖像拖到div上 。
然后進行圖像大小調整。
但是問題是,即使我利用了overflow:hidden和overflow的任何屬性,圖像也會從div中出來。 如何使其在div本身內?
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("application/json", JSON.stringify([ev.target.id,(ev.offsetX || ev.clientX - $(ev.target).offset().left),(ev.offsetY || ev.clientY - $(ev.target).offset().top)]));
}
function drop(ev) {
ev.preventDefault();
var data = JSON.parse(ev.dataTransfer.getData("application/json"));
ev.target.appendChild(document.getElementById(data[0]));
//window.alert( ev.clientX + ',' + ev.clientY);
document.getElementById("img").style.left = ev.clientX - data[1] + 'px';
document.getElementById("img").style.top = ev.clientY - data[2] + 'px';
document.getElementById("img").addEventListener('mousedown', initDrag, false);
return false;
}
var startX, startY, startWidth, startHeight;
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(document.getElementById("img")).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(document.getElementById("img")).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
document.getElementById("drag2").style.width = (startWidth + e.clientX - startX) + 'px';
document.getElementById("drag2").style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
</script>
<body>
<div id="divid" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<img src="test.jpg" id="img" draggable="true" ondragstart="drag(event)"></img>
</body>
<style>
#divid {width:350px;height:170px;padding:10px;border:1px solid #aaaaaa;overflow:auto;}
#img {width:50px;height:50px;padding:10px;position: absolute;}
</style>
如果您引用的ID為“ divid”的div,則您的代碼不在div內。 因此,如果要將div的溢出設置應用於圖像,則image元素必須位於標記之前。 喜歡:
<div id="divid" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="test.jpg" id="img" draggable="true" ondragstart="drag(event)"></img>
</div>
編輯:好的,所以我以前的回答有點誤解了這個問題。 為了后代的緣故,我將其保留。 經過測試,我發現該解決方案非常簡單。 您需要將div的樣式設置為使用position:relative。 否則,絕對定位的圖像將只忽略div的溢出設置。 工作提琴: https : //jsfiddle.net/q9etbdxg/ 。 拖動測試圖像,使其橫跨div的邊緣,您應該看到出現滾動條。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.