图像背景onclick

时间:2012-09-30 15:41:42

标签: javascript html css

我正在尝试创建一个函数,其中单击按钮并为div选择背景图像。以下是我从下面开始的内容,但它似乎没有用,任何人都可以指出我出错的地方...... :)

<style type="text/css">
#txt{
    width: auto;
    height: auto;
    border: solid #000;
    }
</style>

<script type="text/javascript">

    function backg1(){
        var test = new string ();
        test = document.getElementById('txt');
        test.style.backgroundImage="url('cloud.jpg')";
    }

</script>
</head>

<body>
<div id="txt">
<input type="button" value="BG1" onclick="backg1()"/>
</div>

2 个答案:

答案 0 :(得分:2)

由于您的<div>最初只包含按钮输入,因此它没有超出该按钮边界的大小。您需要设置明确的宽度和高度(以及position: relative)以查看背景。

我建议将它们设置为与图像相同的尺寸。

/* in the CSS */
#txt{
    /* use the width, height of your image */
    width: 400px;
    height: 250px;
    position: relative;
    border: solid #000;
}

或者如果您需要动态设置它们:

function backg1() {
    test = document.getElementById('txt');
    test.style.backgroundImage="url('cloud.jpg')";

    // <div>  needs a width & height for the background image to be visible outside the 
    // bounds of the one element contained in the div.
    test.style.width = "400px";
    test.style.height = "250px";
    test.style.position = "relative";
}

答案 1 :(得分:0)

此行有一个javascript错误。 var test = new string();

你可以像var test = new String();然后它应该工作。

此外,我观察到您正在创建字符串对象,然后您将覆盖DOM对象。不知道为什么会这样。你可以创建一个像var test;

这样的变量
相关问题