表示されている画像を任意の画像に変更する

Ads

Result


画像をクリックすると別の任意の画像を選択出来るようになります。

jQuery

(function($) {
	$.fn.imgEdit = function(options) {
		// デフォルト
		var settings = $.extend({
			inputName : "profile-picture",
			form : "#profile",
		}, options);

		$(this).click(function(e){
			
			var target = this;
			// input要素作成
			input = document.createElement('input');
			// Add attributes
			input.setAttribute('type', 'file');
			input.setAttribute('name', settings.inputName);
			input.setAttribute('accept', '.jpg, .jpeg, .png');
			input.setAttribute('style', 'display:none;');
			// クリックイベント
			input.click();
			// 変更
			input.onchange = function() {
				// 前のを削除
				$("#imgEditInput").remove();
				// 新たにIDセット
				input.setAttribute('id', 'imgEditInput');
				// ファイルがあれば読み込み
				if(input.files && input.files[0]){
					var reader = new FileReader();
					reader.onload = function(e) {
				    	$(target).attr('src', e.target.result);
				    }
					reader.readAsDataURL(input.files[0]);
					
					// 入力追加
					$(settings.form).append(input);
				}
				
				
			};
		});

	};

}(jQuery));

html

<form action="" method="POST" id="target-form"></form>
<img src="example.jpg" id="target" />

via

jquery-imgedit

タイトルとURLをコピーしました