简单jquery缩放插件中的中心图像
center image in simple jquery zoom plugin
我正在尝试编写一个非常简单的缩放插件,它应该只有一个放大、缩小按钮和平移功能来移动图像。
现在我已经写了放大和缩小的部分。
我的问题是,我找不到一种方法来将图像集中在"缩放框"中。
这是我迄今为止的代码:
$.fn.zoom = function() {
var img = this;
img.attr("style", "-ms-transform: scale(1); -ms-transform-origin: 0% 0%; -webkit-transform: scale(1); -webkit-transform-origin: 0% 0%").wrap('<div style="width: 400px; height: 400px; overflow: hidden;" class="zoombox" data-scale="1"></div>');
$("body").on("click.zoom", ".zoomin, .zoomout", function() {
if( $(this).hasClass("zoomin") ) {
var zoomFactor = (Number(img.parent().attr("data-scale")) + 0.1).toFixed(1);
} else {
var zoomFactor = (Number(img.parent().attr("data-scale")) - 0.1).toFixed(1);
}
img.parent().attr("data-scale", zoomFactor);
console.log(zoomFactor);
img.css({"-webkit-transform": "scale(" + zoomFactor + ")", "-ms-transform":"scale(" + zoomFactor + ")"});
});
};
Fiddle:
http://jsfiddle.net/xM7r4/1/
我知道这种风格不是最好的,但我只是想让它发挥作用,而不考虑代码的风格。
我如何将图像居中放置在框内,以为以后必须应用平移效果来更改transform-origin
值?
附言:我现在只关心Chrome和IE9的兼容性。
编辑注释
你是对的。在这里,我已经更新为使用transform-origin
。它获取包含div的维度并除以二(以获得包含div的中心点),然后将这些维度传递到图像的css transform-origin
属性中:
http://jsfiddle.net/xM7r4/23/
我已经用不同尺寸的图像进行了测试,它是有效的。
原始
您需要使用margin-left
和margin-top
移动图像,具体取决于放大还是缩小。
http://jsfiddle.net/xM7r4/21/
由于您要将图像增加1%的比例,因此需要相应地移动页边距,放大时为负值,缩小时为负值。
$("body").on("click.zoom", ".zoomin, .zoomout", function() {
var imgWidth = $(img).width();
var imgHeight = $(img).height();
var scaleWidth = Math.floor(imgWidth * 0.01);
var scaleHeight = Math.floor(imgHeight * 0.01);
if( $(this).hasClass("zoomin") ) {
var zoomFactor = (Number(img.parent().attr("data-scale")) + 0.1).toFixed(1);
moveLeft -= scaleWidth;
moveTop -= scaleHeight;
} else {
var zoomFactor = (Number(img.parent().attr("data-scale")) - 0.1).toFixed(1);
moveLeft += scaleWidth;
moveTop += scaleHeight;
}
console.log(moveTop);
console.log(moveLeft);
img.parent().attr("data-scale", zoomFactor);
console.log(zoomFactor);
img.css({"-webkit-transform": "scale(" + zoomFactor + ")", "-ms-transform":"scale(" + zoomFactor + ")", "marginLeft": moveLeft, "marginTop": moveTop});
});
相关文章:
- Three.js,WebGL,渲染六幅图像的全景图
- 图层删除(图像);在 Kinetic.js 中不起作用
- 钛:从Android的相机/图库图像本地保存文件
- 如何在“控制缩放”下的“打开图层”上添加一些图像
- 在图库中按ID查找图像
- 在phoneGap中无法从图库获取图像
- 如何通过在灯箱外单击或在与图像贴图组合时点击esc退出灯箱
- 悬停并选择图像贴图的状态
- 任何比较两个不同位图图像并在javascript中检测不同区域的方法
- 三.js:在立方体贴图中仅更改一张脸的图像
- 按其他图层裁剪图像
- 平板电脑以高分辨率缓慢构建图库图像
- 绘制要素图层面的质心
- Fancybox - 将图像和 iframe 组合在一个图库中
- CSS / JS调整大小/裁剪图库中的图像
- 将谷歌地图另存为图像 - 使用javascript(能够截取屏幕截图)
- 高图表:饼图切片需要背景图像
- 如何在OpenLayers-3上使用SVG图像作为图层
- PhotoSwipe使用图像打开图库
- 图像贴图编辑器