Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 图像背景点击_Javascript_Html_Css - Fatal编程技术网

Javascript 图像背景点击

Javascript 图像背景点击,javascript,html,css,Javascript,Html,Css,我正在尝试创建一个函数,在该函数中,单击一个按钮,并为div选择背景图像。以下是我从下面开始的内容,但它似乎不起作用。有人能指出我哪里出了问题吗…:) #文本{ 宽度:自动; 高度:自动; 边框:实心#000; } 函数backg1(){ var test=新字符串(); test=document.getElementById('txt'); test.style.backgroundImage=“url('cloud.jpg')”; } 由于您的最初只包含按钮输入,因此它的大小不超过该按钮

我正在尝试创建一个函数,在该函数中,单击一个按钮,并为div选择背景图像。以下是我从下面开始的内容,但它似乎不起作用。有人能指出我哪里出了问题吗…:)


#文本{
宽度:自动;
高度:自动;
边框:实心#000;
}
函数backg1(){
var test=新字符串();
test=document.getElementById('txt');
test.style.backgroundImage=“url('cloud.jpg')”;
}
由于您的
最初只包含按钮输入,因此它的大小不超过该按钮的边界。您需要设置明确的宽度和高度(以及
位置:相对
)才能看到背景

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

/* 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";
}
函数backg1(){
test=document.getElementById('txt');
test.style.backgroundImage=“url('cloud.jpg')”;
//需要一个宽度和高度,以便背景图像在外部可见
//div中包含的一个元素的边界。
test.style.width=“400px”;
test.style.height=“250px”;
test.style.position=“相对”;
}

此行出现javascript错误。 var test=新字符串()

您可以将其设置为var test=newstring();那么它应该会起作用


此外,我观察到您正在创建字符串对象,然后使用DOM对象进行覆盖。不知道为什么会这样。您可以创建一个变量,比如var test

您的错误控制台中有错误吗?顺便说一句,
new string()
是没有用的,特别是如果您立即用
getElementById()
中的DOMNode覆盖它,我想您需要将
div\txt
的宽度和高度设置为图像的大小。(也是相对职位)什么有效?设置宽度和高度?我将把它作为一个答案放在下面,您可以将它标记为已接受。CSS为高度和高度赋值width@MichaelBerkowski更不用说它应该是大写的
newstring()
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";
}