[javascript]画像をクリックすると画像をダウンロードする

<a href="#" id="downloadLink">
  <img src="image.jpg" alt="Download" id="downloadButton">
</a>
// Get the image element by its ID
var downloadButton = document.getElementById('downloadButton');

// Function to extract filename from the image source URL
function extractFilename(url) {
    var segments = url.split('/');
    return segments.pop();
}

// Function to trigger the download with the extracted filename
function downloadImage() {
    // Extract the filename from the image source URL
    var src = downloadButton.src;
    var fileName = extractFilename(src);
    
    // Create an anchor element
    var downloadLink = document.createElement('a');
    
    // Set the href attribute to the image source
    downloadLink.href = src;
    
    // Set the download attribute to the extracted filename
    downloadLink.download = fileName;
    
    // Simulate a click on the anchor element to trigger the download
    downloadLink.click();
}

// Add a click event listener to the image to trigger the download
downloadButton.addEventListener('click', downloadImage);

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です