CSS背景图像动态调整大小

CSS background image resize dynamically

本文关键字:调整 动态 背景 图像 CSS      更新时间:2023-09-26

类似的问题我已经处理了一段时间了。我有一个链接,通过css为它分配了一个背景图像。我还有一个悬停图像。我动态调整页面图像的大小,这样它就可以调整图像地图的大小。我正在尝试添加一个Div,这样就会有一个打印机图标,你可以用鼠标悬停在上面。当我让所有东西都保持全尺寸时,它会起作用,但一旦我调整了背景和图像映射弹出窗口的大小,打印机div的大小就会很好,但div中的背景图像不会调整大小。

http://jsfiddle.net/trout0525/qfd58krc/1/

function mainLoad() {
    var imageElement = document.getElementById('jDirBackground');
    imgScale = currentScale(imageElement);
    alert("mainLoad imgScale: " + imgScale);
    var mapElement = document.getElementById('jDirMap');
    var imageMap = new imageMapResize(mapElement, imgScale);
    imageMap.resize();
    var printerIcon = new printerIconResize(imgScale);
    printerIcon.resize();
    return;
}

好吧,我终于找到了一个我认为合理的解决方案。最主要的是CSS3的功能不够强大,无法实现我所希望的功能,所以我回到了HTML的发展图上。

http://jsfiddle.net/trout0525/qfd58krc/2/

我曾希望CSS能够处理图形的大小调整,但它似乎无法做到

onmouseover="imgHover(this)" onmouseout="imgLeave(this)"

以及满足它的代码:

function imgHover (x) {
    x.src = "http://static.wixstatic.com/media/7a35ec_64af7af5864a4f2dad19c8c20855e532.jpg";
}
function imgLeave (x) {
    x.src = "http://www.mailersstore.com/images/SECAP-SA3150.jpg";
}

然后我不得不在JavaScript中处理以下内容的大小调整:

function printerIconResize(imgScale) {
    var position = $('#printerDiv').position();
    var divWidth = $('#printerDiv').width();
    var divHeight = $('#printerDiv').height();
    var iconWidth = $('#printerIcon_link').width();
    var iconHeight = $('#printerIcon_link').height();
    // Get on screen image
    var screenImage = $("#printerIcon_link");
    // Create new offscreen image to test
    var theImage = new Image();
    theImage.src = screenImage.attr("src");
    // Get accurate measurements from that.
    iconWidth = theImage.width;
    iconHeight = theImage.height;
    this.resize = function() {
        var newTop = position.top * imgScale;
        var newLeft = position.left * imgScale;
        var newDivWidth = parseInt((divWidth * imgScale), 10);
        var newDivHeight = parseInt((divHeight * imgScale), 10);
        var newIconWidth = parseInt((iconWidth * imgScale), 10);
        var newIconHeight = parseInt((iconHeight * imgScale), 10);
        $('#printerDiv').offset({ top: newTop, left: newLeft });
        $('#printerDiv').width( newDivWidth );
        $('#printerDiv').height( newDivHeight );
        $('#printerIcon_link').width( newIconWidth );
        $('#printerIcon_link').height( newIconHeight );
        newPosition = $('#printerDiv').position();
        newDivWidth = $('#printerDiv').width();
        newDivHeight = $('#printerDiv').height();
        newIconWidth = $('#printerIcon_link').width();
        newIconHeight = $('#printerIcon_link').height();
        return true;
    };
    window.onresize = this.resize;
}

页面加载和重新加载确实需要一段时间,但这是我现在能想到的最好的。如果你知道更好的方法。。。。

顺便说一句,JSFiddle代码似乎不起作用,但如果你离开网站并尝试它,它应该是好的,除了imgHover和imgLeave实际上在html文件的脚本区域中,而不是在js文件中。

哇!!!该喝啤酒了。(或三个)