When Javascript takes src from an image returns absolute path

Asked

Viewed 1,994 times

0

I have the following HTML5 (only relevant):

<html>
<head>
    <meta charset="UTF-8"/>
    <title>Test</title>
</head>

<body>
<div id="layout">
        <main>
            <section>
                 <ul>
                    <li><img src="Imagens/Foto1.jpg" alt="" onclick="abrirFoto(this.src);"></li>
                </ul>
            </section>
        </main>
    </div>
        <div id="overlay">
            <div id="imgdiv"></div>
        </div>
</body>

With the following Javascript :

function abrirFoto(src) {
var divOpen = document.getElementById('overlay');

var openImg = document.createElement('IMG');
openImg.id = "open";
openImg.setAttribute('src',src);

imgDiv = document.getElementById('imgdiv');
divOpen.style.display = "block";
imgDiv.appendChild(openImg);

});}

It turns out that when Javascript creates the image, the image comes with the value of src as an absolute path,:

<div id="imgdiv">
    <img id="open" src="file:///C:/Users/GustavoR/Desktop/HTML5/14.06%20N-Vermelho%20v2/Imagens/Foto3.jpg">
</div>

Obs:am opening this site a html file from my machine in browser,FF 47.0 .

When/Why does this occur? How to solve?

1 answer

1

This does not occur, it is native. Index src will not return the image attribute. But if you take the attribute src of the image, will return what you typed in the attribute src - Javascript does not modify attributes (except style).

this.getAttribute('src')

The solution in your code would be to modify the HTML line

<li><img src="Imagens/Foto1.jpg" alt="" onclick="abrirFoto(this.src);"></li>

for

<li><img src="Imagens/Foto1.jpg" alt="" onclick="abrirFoto(this.getAttribute('src'));"></li>

... But try not to use online code in HTML.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.