我们有这张照片
我想尝试做的是在刷新或加载时,图片突出显示一个 200x200 的正方形,然后像这样删除图片的其余部分:
如果可能,在没有 javascript 的情况下执行此操作的最简单方法是什么?
最佳答案
这是一个示例,说明如何使用 CSS 和 javascript 执行此操作。这适用于任何高度或宽度的窗口,因为它会从元素中收集值。
我已经对 javascript 进行了评论,但如果您需要其他内容,请告诉我。
演示
// Load image element
image = document.getElementById("random-window-image");
// Get the height and width of the window
window_width = document.getElementById("random-window-wrapper").offsetWidth;
window_height = document.getElementById("random-window-wrapper").offsetHeight;
// Calculate a random left value
temp_left = (image.width - window_width) * Math.random();
// Calculate a random top value
temp_top = (image.height - window_height) * Math.random();
// Apply values to the img
image.style.left = "-" + temp_left + "px";
image.style.top = "-" + temp_top + "px";
#random-window-wrapper {
width: 200px;
height: 200px;
overflow: hidden;
position: absolute;
}
#random-window-image {
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-window-wrapper">
<img id="random-window-image" src="https://placeimg.com/640/480/any">
</div>
关于html - 如何随机化并显示图片的一小部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606443/