开发者

php getElementById

I have a small problem, I would like a div to be displayed when someone hovers over an image, the problem is that this image is inside php, and there for document.getElement开发者_JAVA技巧ById doesn't work. Is there a way to get round this?

<?php echo "<img onmouseover='xxxxxx' src='img/img.png'>" ?>

what goes in x?


You need to create a javascript function on the webpage where this particular line of code is echoed to the client that will handle the onmouseover event, like this:

<html>
<head>
<script language="javascript" type="text/javascript">
function imageSwap() {
   var img = document.getElementById("img1");
   //swap out the image...
}
</script>
</head>
<body>
<?php echo "<img id='img1' onmouseover='imageSwap()' src='img/img.png'>" ?>
</body>
</html>


I have a small problem, I would like a div to be displayed when someone hovers over an image

Make sure the information is accessible to people who don't use a pointing device too

the problem is that this image is inside php, and there for document.getElementById doesn't work.

You have misdiagnosed the problem. PHP runs on the server and its output is sent to the client. It cannot prevent something from working (although it can be written badly so it outputs something you don't expect).

If you think PHP is the cause of your problem then you need to stop asking "Why does the JS embedded in this PHP not work?" and start asking "Why is the JS that is outputted from PHP different from the JS I'm trying to write?"

what goes in x?

It is hard to say without seeing the rest of the code.

It depends on why you can't see the div in the first place. Is it invisible? Is it not displayed? Is it not part of the document? Is it covered up by something else? etc. etc.

As a rule of thumb though, you should avoid intrinsic event attributes in favour of assigning event handlers via JavaScript stored in external files. This is part of unobtrusive JavaScript.


You could change the code of Brian Driscoll to make it dynamic like so:

<html>
<head>
<script language="javascript" type="text/javascript">
function imageSwap(el) {
   var img = el.id;
   //swap out the image...
}
</script>
</head>
<body>
<?php echo "<img id='img1' onmouseover='imageSwap(this)' src='img/img.png'>" ?>
</body>
</html>

This way you will always have the correct id from the image your are hovering on. No matter the amount of images

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜