假设网页上有一个黑白背景,它是风景或城市的图片。现在,在页面上的 div
(其位置不必固定)中,您会看到彩色背景,但只有 div 大小的背景部分
,即 div
用作进入彩色 View 的“窗口”,否则为黑白背景。
仅使用基本网络技术(例如 HTML、CSS、JS)是否可能?我考虑过将 div
的背景设为div
覆盖的背景,但假设网站是屏幕尺寸响应的,当网站切换到较小的屏幕尺寸时,这看起来不会太好 - 彩色图像不会与图像对齐不再。
有什么想法吗?我感谢所有!
编辑 - 一个想法:是否有一个 CSS 属性可用于模糊/加深背景的整个区域,除了被 div 覆盖/包含的区域?
最佳答案
图像使用负边距偏移,负边距等于父 div 的绝对顶部和左侧位置,overflow: hidden;
。
我想这就是你想要的。
http://jsfiddle.net/w17x32dg/2/
var selected = null, // Object of the element to be moved
x_pos = 0,
y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0,
y_elem = 0; // Stores top, left values (edge) of the element
var image;
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
image = document.getElementById('image');
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
image.style.marginLeft = -(x_pos - x_elem) + 'px';
image.style.marginTop = -(y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('color').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
body {
margin: 0;
}
img {
position: absolute;
}
#color {
cursor: move;
position: absolute;
border: 2px solid red;
width: 200px;
height: 200px;
overflow: hidden;
box-sizing: border-box;
}
<img src="http://i.imgur.com/BgewSni.jpg" />
<div id="color">
<img src="http://i.imgur.com/3Ec3jhz.jpg" id="image" />
</div>
关于javascript - 如何: Show a colored portion of an otherwise uncolored background in a div or behind and img?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465068/