JQUERY添加图像属性

时间:2017-07-03 17:16:43

标签: javascript jquery html css

我有以下jquery代码,我想在上传的图像中添加样式。有没有人知道如何在jquery中的src之后添加样式。

Link

var myVideo = document.querySelector("#video1");
myVideo.addEventListener('error', onError);

    function onError(evt) {
       var message = "";
       // The normal error event will not contain the error code
       switch (myVideo.error.code) {
         case null:
           message = 'Unknown error'; // crap, only supported in ie
           break;
         case 1:
           //MEDIA_ERR_ABORTED
           message = " - fetching process aborted by user";
           break;
         case 2:
           //MEDIA_ERR_NETWORK
           message = " - error occurred when downloading";
           break;
         case 3:
           //MEDIA_ERR_DECODE
           message = " - error occurred when decoding";
           break;
         case 4:
           //MEDIA_ERR_SRC_NOT_SUPPORTED 
           message = " - audio/video not supported";
           break;
         default:
           message = " - Unknown";
           break;
       }

       console.log(myVideo.error.code + message);
    };

2 个答案:

答案 0 :(得分:1)

这是一种方法。

let imageStyle = "width:150px";
$("#image-container").append("<img id='theImg' src='" + e.target.result +"' style='"+ imageStyle +"'/>");

这也可以作为

完成
var img = $('<img>');
img.attr('src', e.target.result);
img.attr('style', imageStyle);
img.appendTo('#image-container');

答案 1 :(得分:1)

  

//我想在这里添加syle

您可以简单地添加样式:

"style": "width:100px;height:100px",

$("#fileUpload").on('change', function() {

    if (typeof(FileReader) == "undefined") {
        alert("Your browser doesn't support HTML5, Please upgrade your browser");
    } else {

        var container = $("#image-container");

        //remove all previous selected files
        container.empty();

        //create instance of FileReader
        var reader = new FileReader();
        reader.onload = function(e) {
            $("<img />", {
                "style": "width:100px;height:100px",
                "src": e.target.result
            }).appendTo(container);
        }

        reader.readAsDataURL($(this)[0].files[0]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="container">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-container"> </div>
</div>