我需要做一個圖像比較滑塊,通常的滑塊,你有兩個圖像和一個手柄,允許你顯示/隱藏圖像。 比如這個https://Cody house . co/demo/image-comparison-slider/index . html
關鍵是手柄必須垂直,但不是完全垂直,它必須有一個角度,如下圖所示。然后橫向拖動。你將如何實現這一目標?
請考慮以下情況。
https://jsfiddle.net/Twisty/jzeo4xsm/82/
Java Script語言
$(function() {
function makeClip(width, height, mid) {
//left, top
var half = 50;
var coords = [
[0, 0],
[mid + half, 0],
[mid - half, height],
[0, height]
];
return coords;
}
function setClipStyle(target, left) {
var coords = makeClip($(target).width(), $(target).height(), left);
console.log(coords);
var parts = [];
parts.push(coords[0][0] + "px " + coords[0][1] + "px");
parts.push(coords[1][0] + "px " + coords[1][1] + "px");
parts.push(coords[2][0] + "px " + coords[2][1] + "px");
parts.push(coords[3][0] + "px " + coords[3][1] + "px");
var style = 'polygon(' + parts.join(",") + ')';
console.log(style);
$(target).data("mid", left).css("clipPath", style);
}
setClipStyle(".img-over img", 300);
$(".slide-handle").draggable({
axis: "x",
containment: [-20,0,580,0],
drag: function(e, ui) {
setClipStyle(".img-over img", ui.position.left + 30);
}
});
});
這就用clip-path操作了圖像的CSS。你需要檢查瀏覽器的兼容性。我還使用jQuery UI來簡化拖動操作。
參考資料:
https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path https://api.jqueryui.com/draggable/ https://css-tricks.com/almanac/properties/c/clip-path/