Как вернуть код для замены тегов кода переведенным текстом, между которыми был переведен Google Translate?Html

Программисты Html
Ответить
Anonymous
 Как вернуть код для замены тегов кода переведенным текстом, между которыми был переведен Google Translate?

Сообщение Anonymous »

Как вернуть код для замены тегов кода переведенным текстом между ними, который был переведен Google Translate?
Google Translate не переводил текст между тегами

Код: Выделить всё

 и . Javascript, упомянутый в этом вопросе (ниже), правильно заменяет теги  и  на  и  соответственно, а элемент Google Translate также правильно переводит текст между этими тегами, но я не могу снова заменить теги  и  на  и Теги  после перевода Google Translate (с переведенным текстом между тегами)
Вопрос, заданный в разделе Как заставить Google Translate переводить текст между тегами  и  на моей веб-странице? заключается в переводе текста между  и тегами, и никто не удосужился на него ответить. В этом вопросе задается вопрос, как заменить  и теги обратно на  и теги после перевода (с переведенным текстом между тегами).  Этот вопрос отличается
Я пытался обнаружить перевод и вернуть теги с переведенным текстом между тегами (первоначально между тегами  и ), но он не возвращается
[b]HTML[/b]
html
☰ Menu
Javascript
Javascript


// Function to replace with across the document
function replaceCodeWithSpan() {
console.log("Replacing code with span...");
const codes = document.querySelectorAll('code');
codes.forEach(code => {
const span = document.createElement('span');
// Copy attributes and content
Array.from(code.attributes).forEach(attr => span.setAttribute(attr.name, attr.value));
span.innerHTML = code.innerHTML;
// Insert new span before the code and remove the code
code.parentNode.insertBefore(span, code);
code.parentNode.removeChild(code);
});
}

// Function to apply the data-original-tag attribute
function applyOriginalTagAttribute() {
// Select all elements that have a specific class added by Google Translate
// (e.g., 'notranslate' or a specific class you might have added to original elements)
// Or, more generally, iterate through all elements and apply a heuristic.
// For this example, we'll assume a class 'original-code' was present on the elements.
const spans = document.querySelectorAll('span.original-code');

spans.forEach(span => {
// Check if the element was likely a element before translation.
// This might involve checking for specific content patterns, or relying on a class
// that was present on the original element and persisted through translation.
// For a robust solution, you might need to pre-process or add unique identifiers.

// For simplicity, if we assume the original element had a class 'original-code',
// and this class is retained by the after translation:
if (span.classList.contains('original-code')) {
span.setAttribute('data-original-tag', 'code');
// You might also remove the 'original-code' class if it's no longer needed on the
// span.classList.remove('original-code');
}
});
}

// Function to revert back to
function revertSpanToCode() {
console.log("Reverting span to code...");
const spans = document.querySelectorAll('span');
spans.forEach(span => {
// Ensure we only target spans that were part of our replacement logic if possible,
// or ensure no other spans on the page are accidentally affected.
// A better approach might be to add a specific class during the initial replacement.

// For this general example, we assume we want to revert all spans back to codes (which might be too broad).
// A safer way is using a specific marker class or ID.
// Assuming we add a class 'translated-span' during replacement:
if (span.classList.contains('translated-span')) {
const code = document.createElement('code');
Array.from(span.attributes).forEach(attr => code.setAttribute(attr.name, attr.value));
code.innerHTML = span.innerHTML;
span.parentNode.insertBefore(code, span);
span.parentNode.removeChild(span);
}
});
}

// Use MutationObserver to detect Google Translate completion
const observerCallback = (mutationsList, observer) => {
const htmlEl = document.documentElement;
const isTranslated = htmlEl.classList.contains('translated-ltr') || htmlEl.classList.contains('translated-rtl');

if (isTranslated) {
// Page has been translated
console.log("Google Translate detected. Applying span replacements.");
replaceCodeWithSpan();
// You might want to disconnect the observer once done if you don't need further dynamic updates
// observer.disconnect();
} else {
// Translation was likely reverted to original language
console.log("Google Translate reverted or not active. Reverting code replacements if any.");
revertSpanToCode();
}
};

// Configuration for the observer: watch for attribute changes on the element
const observerConfig = { attributes: true, attributeFilter: ['class'], childList: false, characterData: false };
const observer = new MutationObserver(observerCallback);

// --- Your existing Google Translate Element initialization code should be here ---
// This part should be after the definition of the functions above.
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en', // Set your original page language
layout: google.translate.TranslateElement.InlineLayout.VERTICAL // Change this line
}, 'google_translate_element');
setTimeout(revertSpanToCode, 3000); // Adjust delay as needed
}
// --------------------------------------------------------------------------------

// Start observing the element for class changes (which the translator does)
observer.observe(document.documentElement, observerConfig);

// Function to revert the span back to code
function revertTranslation() {
var translatedSpans = document.querySelectorAll('span[data-original-tag="code"]');
translatedSpans.forEach(function(span) {
var originalTag = span.getAttribute('data-original-tag');
var code = document.createElement(originalTag);
code.innerHTML = span.innerHTML;
span.parentNode.replaceChild(code, span); // Replace span with original code tag
});
}


Подробнее здесь: https://stackoverflow.com/questions/798 ... ed-text-in
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»