1

ボタンをクリックして背景画像を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>
4

2 に答える 2

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";
}
于 2012-09-30T16:11:53.923 に答える
0

この行に JavaScript エラーがあります。var test = 新しい文字列 ();

var test = new String(); のようにすることができます。その後、動作するはずです。

さらに、文字列オブジェクトを作成していて、DOM オブジェクトでオーバーライドしていることに気付きました。なぜそれがそんなに好きなのかわからない。var test; のような変数を作成するだけです。

于 2012-10-01T05:14:01.660 に答える