简体   繁体   English

如何将CSS参数链接到javascript img?

[英]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. 我在网页上添加了带有Javascript的图像,但是我不知道如何修改或放置它。 How can I link CSS to the image, or can I modifiy it without CSS? 如何将CSS链接到图像,或者在没有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. jQuery使这变得非常容易。 Apply any styling you want on the image in the style quotes of the image 在图像的style引号中将所需的任何样式应用于图像

<!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, Javascript可以设置元素的属性,

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

https://www.w3schools.com/jsref/met_element_setattribute.asp 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 另外,如果您不想使用内联CSS,则可以将CSS添加到CSS文件中,并使用jquery为图像提供一个类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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