首页 > 解决方案 > 使用 javascript 在 div 中设置图像,使用 backgroundImage

问题描述

我有一个<img>加载了静态和可缩放图像的图像。

我有一个功能,每次检测滚轮事件并计算图像宽度和高度时更新一些组件,在 img 元素中设置样式属性后,最后在结果中设置 src<div>

而不是放大图像,图像在结果 div 中移动到一侧。

功能:

function updateBgStyle() {
            //alert('updateBgStyle');
            if (bgPosX > 0) {
                bgPosX = 0;
            } else if (bgPosX < width - bgWidth) {
                bgPosX = width - bgWidth;
            }

            if (bgPosY > 0) {
                bgPosY = 0;
            } else if (bgPosY < height - bgHeight) {
                bgPosY = height - bgHeight;
            }

            img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
            img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';

            var x = document.getElementById('myimage');
            var img2 = document.createElement("IMG");

            img2.src = '../../RESOURCES/images/remoteAgent/473_180420160608_HJF4013_2.jpg';

            //var oldImg = document.getElementById('myimage');
            document.getElementById('myresult').style.backgrounSize = img.style.backgroundSize;
            document.getElementById('myresult').style.backgroundPosition = img.style.backgroundPosition;
            document.getElementById('myresult').style.backgroundImage = "url('" + img2.src + "')";

        }

xhtml:

<p:panelGrid columns="1" style="border: 2px solid white;float: right;
    border: 2px solid white;">
    <script>
        // Initiate zoom effect:
        //imageZoom("myimage", "myresult"); 
        wheelzoom(document.querySelector('img.zoom'));

    </script>
    <img class="zoom" id="myimage" onmouseout="atualizaImg()"
        src="../../RESOURCES/images/remoteAgent/473_180420160608_HJF4013_2.jpg"
                            style=" width: 340px; margin-top: 20px;"/>

    <div id="myresult" src="../../RESOURCES/images/remoteAgent/bolaVerde.png"
        style="width: 340px;height: 200px; align: center; border: 1px solid black;"/>   
    </p:panelGrid>

标签: javascript

解决方案


推荐阅读