使用backgroundImage在div中使用javascript设置图像

时间:2019-04-26 17:48:42

标签: javascript

我有一个<img>,其中加载了静态且可缩放的图像。

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

该图像不是在放大图像,而是在结果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>

0 个答案:

没有答案