简体   繁体   中英

How can I link CSS parameters to a javascript img?

I added an image with Javascript to a webpage, but I don't know how to modify it or place it. How can I link CSS to the image, or can I modifiy it without CSS?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PingPongKép</title>
    <link rel="stylesheet" href="CSS/style.css">
</head>
<body>



 <script>

    function ilonaKep() {
  var img = new Image();
  img.src = 'img/ilona.jpg';
  document.body.appendChild(img);


}


    </script>

<p>Let's See the image

   <script>
    ilonaKep();
    </script>

   </p>


</body>
</html>

JQuery makes this quite easy. Apply any styling you want on the image in the style quotes of the image

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>

    <body>
        <p> Lets see the image: </p>

        <script>
            window.onload = function(){
                addImage();

                function addImage() {
                    $('body').append('<img style="any css styling in here" src="img/ilona.jpg">');
                }
            }
        </script>
    </body>
</html>

Javascript has the ability to set an element's attribute,

img.setAttribute("style", "background-color: red;");

https://www.w3schools.com/jsref/met_element_setattribute.asp

Alternatively if you don't want inline CSS, you could add the CSS to your CSS file and give the image a class using jquery

$("img").addClass("myImage");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM