简体   繁体   English

我无法通过输入类型文件中的onchange来更改div背景图像-通过IE和Safari的Javascript-在FF和Chrome中有效

[英]I Can't get div background image to change with onchange in a input type file - by Javascript for IE and Safari - works in FF and Chrome

if you open the fiddle http://jsfiddle.net/FyJR3/3 in both Firefox and IE and when you select a local image - The Div background image does not disply in ie - but it does display in firefox - so i am looking to find a solution to this cross browser incompatability :) - also note it does NOT use jQuery - it uses prototype.js and scriptaculous.js 如果您在Firefox和IE中都打开小提琴http://jsfiddle.net/FyJR3/3并选择了本地图像-Div背景图像不会显示在ie中-但它确实会显示在firefox中-所以我正在寻找找到针对这种跨浏览器不兼容的解决方案:)-还请注意,它不使用jQuery-它使用prototype.js和scriptaculous.js

I am a novice at Javascript and have modified and used others code from stackoverflow.com, to make a Visual Cropper for my site - I use the Input type=File 我是Java新手,已经修改并使用了stackoverflow.com上的其他代码来为我的网站制作Visual Cropper-我使用Input type = File

<input id="attach1" name="attach1" type="file" size=60 style="width:390px;">

This is the divs i am trying to change (that wont work in IE and Safari) Is working in firefox and Chrome - the extra <div></div> were a suggestion from another persons answers on this board to a similar (not the same problem) - they made no difference and can be removed. 这是我要更改的div(在IE和Safari中不起作用)在Firefox和Chrome中工作-额外的<div></div>是其他人在此板上的类似建议(不是同样的问题)-它们没有区别,可以删除。 clear512px.png is just a clear 512px square overlay to hold the div open and at size for the cropping. clear512px.png只是一个清晰的512px正方形叠加层,用于保持div处于打开状态并可以进行裁剪。 (Code wont work without it - so far in firefox and chrome) (如果没有它,代码将无法工作-到目前为止,仅在Firefox和chrome中)

<div style="width:512px; height:512px;">
    <div></div>
    <div id="theImageToCrop" align="center" style="background-image: url(../pics/No-Image.jpg); background-position:center; background-repeat:no-repeat; background-size:contain; max-height:512px; max-width:512px; width:100%; border: 1px solid #808080; position: relative;">
        <div></div>
        <div id="testWrap" style="height:512px; width:512px; text-align:center; vertical-align:middle;">
        <div></div>
            <img src="../cropper/tests/clear512px.png" src= alt="test image" id="testImage" style="width:100%;" />
        </div>
    </div>
</div>

I have the below two scripts at the bottom of the page just before the </body> tag - This works in chrome and Firefox - but not in IE and Safari 我在页面底部的</body>标记之前有以下两个脚本-在chrome和Firefox中有效-在IE和Safari中不可用

<script type="text/javascript">
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
alert(i + " " + files[i]);
      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
          reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
         var div0 = document.getElementById('theImageToCrop');
            div0.style.backgroundImage = "url(" + e.target.result + ")";
       };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }  

  document.getElementById('attach1').addEventListener('change', handleFileSelect, false);
</script>

<script type="text/javascript">
(window.onload = function(){

var img = document.getElementById('theImageToCrop').style.backgroundImage;
img.onload = function() {
    if(img.height > img.width) {
        img.height = '100%';
        img.width = 'auto';
    }
};

}());
</script>

What I need to do is to display the file(image) from the the input and display it in the ID="theImageToCrop" Div - so as the user can see it - and the rest of the code to zoom and crop is functional - its hosted on a windows server 2008 - My primary server code is ASP classic - with smatterings of ASP.net, obviously Javascript (My weak point) and also loaded and using "prototype.js" and "scriptaculous.js" and "cropper.js" script sources - NO jQuery use. 我需要做的是显示输入中的文件(图像),并在ID =“ theImageToCrop” Div中显示它-这样用户就可以看到-其余用于缩放和裁剪的代码都可以正常工作-它托管在Windows Server 2008上-我的主要服务器代码是ASP经典-带有少量ASP.net,显然是Javascript(我的弱点),并且还加载并使用了“ prototype.js”,“ scriptaculous.js”和“ cropper”。 js”脚本来源-无需jQuery使用。

I am still a novice at JS so please can you make the answer/reasoning as simple as possible 我仍然是JS的新手,所以请您尽可能简化答案/理由

Your help on this is very appreciated -Thanks in Advance 非常感谢您的帮助-在此先感谢

          • Addded Full code below below * * * * * * 下面添加了完整的代码* * * * * *

Below is full code of a lighter page with which I am needing to get the results - this is live at http://www.VintageAntiqueRetro.com/testcropping.asp - but page is stripped of the upload function (that upload section works a treat) - I just need to be able to select 1 (one) file and have the div change in all browsers. 下面是一个较浅的页面的完整代码,我需要使用该页面来获取结果-该页面实时显示在http://www.VintageAntiqueRetro.com/testcropping.asp-但该页面已删除了上传功能(该上传部分适用于请)-我只需要能够选择1(一个)文件,并在所有浏览器中更改div。 Thanks Guys :) 多谢你们 :)

<%@ Language=VBScript %> 
<% option explicit 
Response.Expires = -1
Server.ScriptTimeout = 600
Session.CodePage  = 65001
Dim thispageaddress, adStateOpen, sPicNum, oldfile, fm, itisdone, jpeg
Dim errMsgs, verified, ulog, thelistingnum, origdir, smdir, meddir, lgdir
Dim lwidth, lheight, aspectratio, newheight, newwidth, SaveFile, newPath
Dim filepath, DesiredWidth, DesiredHeight, quality, newfile, resizescale
Dim dy, dy1, dx, dx1, sx1, sx2, sy1, sy2
Dim swidth, sheight, sx1a, sx2a, sy1a, sy2a, sheighta, swidtha, blankspace
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../login.css">
<script src="js/admin.js" type="text/javascript" language="javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js" type="text/javascript"></script>
<script src="cropper/cropper.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
    function onEndCrop( coords, dimensions ) {
        $( 'x1' ).value = coords.x1;
        $( 'y1' ).value = coords.y1;
        $( 'x2' ).value = coords.x2;
        $( 'y2' ).value = coords.y2;
        $( 'width' ).value = dimensions.width;
        $( 'height' ).value = dimensions.height;
    }

    // with a supplied ratio
    Event.observe( 
        window, 
        'load', 
        function() { 
            new Cropper.Img( 
                'testImage', 
                { 
                    ratioDim: { x: 500, y: 500 }, 
                    displayOnInit: true, 
                    onEndCrop: onEndCrop 
                } 
            ) 
        } 
    );
</script>

<style type="text/css">
    input { 
        width: 40px;
    }

</style>

<script type="text/javascript">
(function() {

var img = document.getElementById('theImageToCrop').backgroundImage;
img.onload = function() {
    if(img.height > img.width) {
        img.height = '100%';
        img.width = 'auto';
    }
};

}());
</script>

<script>
function onSubmitForm() {
    var formDOMObj = document.frmSend;
    if (formDOMObj.attach1.value == "")
        alert("Please press the Browse button and pick a file.")
    else
        return true;
    return false;
}
</script>
<TITLE>Upload Listing Pics to the server</TITLE>
</HEAD>
<div style="padding:25px;">
    <form name="frmSend" method="POST" enctype="multipart/form-data" accept-charset="utf-8" action="testcropping.asp?" onSubmit="return onSubmitForm();">
    <Strong>Upload Image File to Server: </Strong>&nbsp; (Max Image Size per upload is 8 MB, Images will be resized)
    <br><br>
    <strong>1</strong>/ Choose an image &nbsp; <input id="attach1" name="attach1" type="file" size=60 style="width:390px;"><br>
    <br /> 
    <strong>2</strong>/ Position/zoom the crop box<font style="font-size:9px;"> (use mouse on corners to zoom, hold left mouse button and drag to move position)</font><br />
    <div style="width:512px; height:512px;"><div></div>
    <div id="theImageToCrop" align="center" style="background-image: url(../pics/No-Image.jpg); background-position:center; background-repeat:no-repeat; background-size:contain; max-height:512px; max-width:512px; width:100%; border: 1px solid #808080; position: relative;"><div></div>
        <div id="testWrap" style="height:512px; width:512px; text-align:center; vertical-align:middle;"><div></div>
            <img src="../cropper/tests/clear512px.png" src= alt="test image" id="testImage" style="width:100%;" />
        </div>
    </div>
</div>

<div style="padding-top:5px;">
        <label for="x1">x1:</label>
        <input type="text" name="x1" id="x1" />
        &nbsp;&nbsp; 
        <label for="y1">y1:</label>
        <input type="text" name="y1" id="y1" />
        &nbsp;&nbsp; 
        <label for="x2">x2:</label>
        <input type="text" name="x2" id="x2" />
        &nbsp;&nbsp; 
        <label for="y2">y2:</label>
        <input type="text" name="y2" id="y2" />
        &nbsp;&nbsp; 
        <label for="width">width:</label>
        <input type="text" name="width" id="width" />
        &nbsp;&nbsp; 
        <label for="height">height</label>
        <input type="text" name="height" id="height" />
</div>      
        <br /><strong>3</strong>/ Upload your image to server &nbsp; 

    <input style="margin-top:4px; background-color:#E9E9E9; width:150px;" type=submit value="Click here to Upload">
    </form>
    <br />
</div>
<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
          reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
         var div0 = document.getElementById('theImageToCrop');
            div0.style.backgroundImage = "url(" + e.target.result + ")";
       };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }  

  document.getElementById('attach1').addEventListener('change', handleFileSelect, false);
</script>
</BODY>
</HTML>

I have the fiddle example for you to look at in different browsers(ff/ie/chrome/safari) here --> jsfiddle.net/FyJR3/3/ 我有一个小提琴示例供您在不同的浏览器(ff / ie / chrome / safari)中查看-> jsfiddle.net/FyJR3/3/

so in summary 所以总的来说

if you open the fiddle in both Firefox and IE and when you select a local image - The Image does not disply in ie - but it does display in firefox - so i am looking to find a solution to this cross browser incompatability :) - also note it is NOT jQuery - it is prototype.js and scriptaculous.js - Thanks 如果您同时在Firefox和IE中打开小提琴并且选择了本地图像-图像不会显示在ie中-但它确实会显示在firefox中-因此,我正在寻找一种解决此跨浏览器不兼容问题的方法:)-也注意它不是jQuery-它是prototype.js和scriptaculous.js-谢谢

The code you're using seem more complicated then it has to be. 您正在使用的代码似乎必须要复杂得多。 If you only need the user to load a single file then we don't have to loop over multiple files. 如果您只需要用户加载单个文件,那么我们就不必循环多个文件。

$('#file').on('change', function(evt){
    var file = evt.target.files[0];
    if(file.type.match('image.*')){
        var reader = new FileReader();
        reader.onload = (function(file){
            return function(e){
                $('#view').css({
                    'background-image': 'url(' + e.target.result +')'
                });
            }
        })(file);
    }

    reader.readAsDataURL(file);
})

try this fiddle 试试这个小提琴

Not an answer, just a short explanation: Internet Explorer < 10 does not support the File API, which you use when trying to get input.files[0]. 这不是一个答案,只是一个简短的解释:Internet Explorer <10不支持File API,在尝试获取input.files [0]时会使用它。 So the type will never match, and the reader is never set (although I do believe the reader is also unsupported in IE). 因此,类型将永远不会匹配,并且永远不会设置阅读器(尽管我确实相信IE也不支持阅读器)。 Unfortunately I am looking into a similar issue, most mentioned options are using flash or upload the image to a temp file. 不幸的是,我正在研究类似的问题,大多数提到的选项是使用Flash或将图像上传到临时文件。

IE support for Fiel API: http://caniuse.com/#search=file%20api IE对Fiel API的支持: http : //caniuse.com/#search=file%20api

File API: http://www.w3.org/TR/FileAPI/ 档案API: http//www.w3.org/TR/FileAPI/

暂无
暂无

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

相关问题 Javascript适用于FF / IE,但不适用于Chrome / Safari - Javascript works in FF / IE but not Chrome / Safari 我的 Javascript 适用于 IE FF 和 Safari,但不适用于 Chrome - My Javascript works on IE FF & Safari, but not Chrome 用于动态更改图像的Javascript代码可在IE,FF,Chrome等中正常运行:( - Javascript code to dynamically change image works in IE not FF, Chrome etc :( 无法在Chrome,Safari和FF中使.focus()集中于具有ID的输入 - Can't get .focus() to focus on an input with an id in Chrome, Safari, and FF JQuery - Chrome 中的背景图像旋转问题(仅在 F5 刷新后有效)。 在 FF、Safari、IE 中没有问题 - JQuery - Background image rotation issues in Chrome (works only after F5 refresh). No problems in FF, Safari, IE 在IE 9之前无法使用的Javascript / jquery代码在FF,Chrome,Safari中正常运行 - Javascript/jquery code that doesn't work prior to IE 9. Works fine in FF, Chrome, Safari iFrame 在 Chrome 中不起作用(在 FF、IE 和 Safari 中工作正常) - iFrame doesn't work in Chrome (works fine in FF, IE and Safari) 更改div背景图片,js在chrome中有效,但在ie或firefox中不起作用吗? - Change div background image, js works in chrome but not ie or firefox? Javascript在Chrome上有效,但在IE或FF上无效 - Javascript works on Chrome, but no on IE or FF onChange不会在Safari的下拉列表中触发,但可以在IE,FF,Chrome和Opera中使用 - onChange not firing in a drop down listing in Safari, works in IE, FF, Chrome & Opera
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM